Play with Reactive Slick: A Simple CRUD application in Play! framework using Slick 3.0

Recently Typesafe released Slick 3.0.0-RC1, the first release candidate for “Reactive Slick”. Reactive Slick has many new features like Support for Reactive Streams API, a new API for composing and executing database actions and many more.

Before moving forward, we recommended you to go through the Slick 3.0.0-RC1 Upgrade guide. So, that you can get a hint of major changes in Slick 3.0.

In this post, we will see how to build a Reactive Play application with Reactive Slick. In order to build a simple CRUD application in Play framework using Reactive Slick (Slick-3.0.0-RC1) we need to follow these steps:

1) Run activator new play-reactive-slick play-scala to create a new Play application.

2) Add following dependencies in build.sbt file

"com.typesafe.slick" %% "slick" % "3.0.0-RC1"
"org.slf4j" % "slf4j-nop" % "1.6.4"
"postgresql" % "postgresql" % "9.1-901.jdbc4"

Here we are using PostgreSQL as database. So, if you have not installed it yet, you can download it from here.

3) Next, we need to add bidirectional mapping of our case class with the table, like this:

case class Employee(id: Option[Long], name: String, address: String, dob: Option[Date], joiningDate: Date, designation: Option[String])

class Employees(tag: Tag) extends Table[Employee](tag, "EMPLOYEE") {

 implicit val dateColumnType = MappedColumnType.base[Date, Long](d => d.getTime, d => new Date(d))

 def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
 def name = column[String]("name")
 def address = column[String]("address")
 def dob = column[Date]("date_of_birth")
 def joiningDate = column[Date]("joining_date")
 def designation = column[String]("designation")

 def * = (id.?, name, address, dob.?, joiningDate, designation.?) <> (Employee.tupled, Employee.unapply _)

Important thing to note in above mapping is that we have omitted O.Nullable/O.NotNull. The reason behind it is that both O.Nullable/O.NotNull are deprecated in Slick-3.0.0-RC1. Instead, we have provided the mapping for optional fields in projection itself.

4) Then, we can write a Database Access Object (DAO) to perform CRUD operations:

object EmployeeDAO {

  val employees = TableQuery[Employees]

  def db: Database = Database.forDataSource(DB.getDataSource())

  def filterQuery(id: Long): Query[Employees, Employee, Seq] =
    employees.filter( === id)

  def findById(id: Long): Future[Employee] =
    finally db.close

  def insert(employee: Employee): Future[Int] =
    try += employee)
    finally db.close

  def update(id: Long, employee: Employee): Future[Int] =
    finally db.close

  def delete(id: Long): Future[Int] =
    finally db.close

As we can see in above code that now Slick returns result in Future. Also, now the database instance db have an associated connection pool and thread pool, so, it is important to call db.close when we are done using it.

5) At last, we need to provide Asynchronous Action response in controller. Example:

def delete(id: Long): Action[AnyContent] = Action.async { implicit request =>
 val futureEmpDel = EmployeeDAO.delete(id) { result => Home.flashing("success" -> "Employee has been deleted") }.recover {
   case ex: TimeoutException =>
     Logger.error("Problem found in employee delete process")

Here we are using Action.async to handle Future response from database.

In this way we can build a simple CRUD application in Play framework using Reactive Slick. For more information on Reactive Slick click here.

To download a demo Application click here.

Posted in Agile, Future, Non-Blocking, Play Framework, Reactive, Scala, Slick, Web | Tagged , , , , | Leave a comment

Handling Twitter share response

Twitter  share is a way to allow user  to share website / tweet on the twitter . There are various methods to share data  on twitter , but here we are using  javascript method .We can customize tweet  using data attributes .
Followings are steps need to be followed
1) Add javascript in file . It would be better to add javascript  just below <body> .

window.twttr=(function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],t=window.twttr||{};if(d.getElementById(id))return;js=d.createElement(s);;js.src="";fjs.parentNode.insertBefore(js,fjs);t._e=[];t.ready=function(f){t._e.push(f);};return t;}(document,"script","twitter-wjs"));

2) Add below anchor tag  where you would like to render the Tweet Button .


<a class="twitter-share-button" href="" data-size="small" data-url="" data-text="Hello" data-count="none" >Tweet</a>

To display count box (number of share) remove data-count=”none” attribute  or set data-count=”horizontal”
3) If you would like to handle the tweet response , you need to bind the twitter response by using following script .


<script src=""></script>
<script>'tweet' , function(event) {
  // do somethings here
alert("Tweet has been successfully posted");
</script> method would be called when tweet posted successfully .


Posted in JavaScript, Tutorial, Web | Leave a comment

Play-Slick-PostgreSQL: Reactive Play application with Slick extensions for PostgreSQL


Building Reactive Play application with Slick extensions for PostgreSQL

This is a classic CRUD application, backed by a PostgreSQL database. It demonstrates:

  • Handling asynchronous results, Handling time-outs
  • Achieving, Futures to use more idiomatic error handling.
  • Accessing a JDBC database, using Slick.
  • Achieving, table pagination and sorting functionality.
  • Embedded JS & CSS libraries with WebJars.
  • Play and Scala-based template engine implementation
  • Integrating with a CSS framework (Twitter Bootstrap 3.1.1). Twitter Bootstrap requires a different form layout to the default one that the Play form helper generates, so this application also provides an example of integrating a custom form input constructor.
  • Bootswatch-Yeti with Twitter Bootstrap 3.1.1 to improve the look and feel of the application

Continue reading

Posted in Bootstrap, Future, JavaScript, jQuery, Non-Blocking, Play Framework, Reactive, Scala, Slick, Web | Tagged , , , , | 3 Comments

Meetup: Introduction to Play Framework !!

Reactive Application Programmers in Delhi NCR

Hi Folks,

Knoldus have organized an one hour session on 4th Feb 2015 at 5:00 PM. Topic is  Introduction to Play Framework. So many people have joined and enjoyed the session. I am going to share that slide here. Please let me know if you have any question related to linked slide.

Slide: Introduction to Play framework

Posted in Play Framework, Reactive, Scala, Tutorial | Tagged , , | 1 Comment

Knolx: Extractors & Implicit conversions

In this presentation, I have explained few features of advance scala. The topics I have covered here are the Implementations of extractors, Implicit conversions, parameters and implicit context and update function with code snippet.

In the first part of presentation I have shown how well extractors can be used to decompose various kind of data structure in pattern matching.In the second part I have discussed about what rules should be followed while using implicit conversions, different ways to implement it and how implicit conversations can be very useful with generic functions.


Posted in Scala | Leave a comment

Knolx : Functions In Scala

In this presentation, we are going to discuss about Function Literal,  Higher Order Function, Partial Function, Partial Applied Function, Nested Function, Closures.


Posted in Scala | Tagged | Leave a comment

Knolx : Collections In Scala

Harsh Sharma, one of our intern who joined us on January 15, 2015 presented a knolx on “Collection In Scala”. He shared whatever he has learnt in his 1 month internship period. We appreciate that. Keep up learning and sharing your knowledge.

Posted in Akka, Cloud, Future, Java, Non-Blocking, Play Framework, Scala, Web | Leave a comment

Knolx Session : Jenkins CI

Jenkins is an open source continuous integration (CI) tool written in Java. Continuous integration (CI) is the practice, in software engineering, of merging all developer working copies with a shared mainline several times a day. The main aim of CI is to prevent integration problems.
Jenkins provides continuous integration services for software development. It is a server-based system running in a servlet container such as Apache Tomcat.

Posted in Scala | 1 Comment

Integrating sending mail functionality with LogBack in Scala

Few days ago, I had the requirement that whenever there will be an exception in the application, we should get an email for this. Earlier, I was just logging the error log using LogBack :

val logger: Logger = LoggerFactory.getLogger(this.getClass())

To do this, there are 2 ways :
1. Use the email sending code at every place wherever i have used logger.error.
2. Use the SMTPAppender of logback which sends email by itself whenever logger.error will be called.

So I tried with 2nd solution.

SMTPAppender :
We have to provide following settings for this in logback.xml :

<appender name="EMAIL" class="">
		<subject>ERROR: %logger{20} - %m</subject>
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%date %-5level %logger - %message%n</pattern>
	<root level="info">
		<appender-ref ref="EMAIL" />

There is one important thing to be remember, email would work only for logger.error(). Other than this ,it would not be work
If you want to append one more logger then do as follows :

<logger name="" level="debug">
		<appender-ref ref="CONSOLE" /

Code for this sample is present on the Knoldus Github
For more details, click here

Posted in Akka, Cloud, Java, Play Framework, Reactive, Scala, Web | 2 Comments

Easiest Way To Insert Scala Collection into PostgreSQL using Slick

Few days ago, I had a scenario, in which I had to insert scala collection into postgreSQL using Slick. My postgreSQL table has some columns with data types such as Arrays, hstore  etc..
I tried to do this using slick, but didn’t get success. After beating my head whole day, I found a solution.
I found a slick extension slick-pg, which supports following postgreSQL types:-

  • Date/Time
  • Enum
  • Range
  • Hstore
  • LTree
  • JSON
  • Inet/MacAddr
  • text Search
  • postgis Geometry

In this blog, I have explained how to insert Scala collection into PostgreSQL using Slick through an example.  In this example,  there is a student table, which has 4 columns


CREATE TABLE student (
id     int,
name   varchar(254) NOT NULL,
hobbies  text[],
marks hstore

Here hobbies is Array of String and marks is hstore(Set of key-value pair).

As suggested here , I created a trait MyPostgresDriver  and integrated with PostgresDriver like this:-

trait MyPostgresDriver extends PostgresDriver
  with PgArraySupport
  with PgHStoreSupport {
  override lazy val Implicit = new ImplicitsPlus {}
  override val simple = new SimpleQLPlus {}
  trait ImplicitsPlus extends Implicits
    with ArrayImplicits
    with HStoreImplicits
  trait SimpleQLPlus extends SimpleQL
    with ImplicitsPlus

Then I mapped my table like this:-

class StudentTable(tag: Tag) extends Table[Student](tag, &quot;student&quot;) {
  def id = column[Int](&quot;id&quot;, O.PrimaryKey)
  def name = column[String](&quot;name&quot;)
  def hobbies = column[List[String]](&quot;hobbies&quot;, O.Default(Nil))
  def marks = column[Map[String, String]](&quot;marks&quot;)
  def * = (id, name, hobbies, marks) &lt;&gt; (Student.tupled, Student.unapply)

After running command sbt run, I was able to store data in postgres.


For complete example, please go here

Posted in Scala, sql | Tagged , , , | 4 Comments