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 === id)

  def findById(id: Long): Future[Employee] =
    try db.run(filterQuery(id).result.head)
    finally db.close

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

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

  def delete(id: Long): Future[Int] =
    try db.run(filterQuery(id).delete)
    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)
 futureEmpDel.map { result => Home.flashing("success" -> "Employee has been deleted") }.recover {
   case ex: TimeoutException =>
     Logger.error("Problem found in employee delete process")
     InternalServerError(ex.getMessage)
   }
 }

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> .

<script>
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.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);t._e=[];t.ready=function(f){t._e.push(f);};return t;}(document,"script","twitter-wjs"));
</script>

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

 

<a class="twitter-share-button" href="https://twitter.com/share" data-size="small" data-url="http://knoldus.com" 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="https://platform.twitter.com/widgets.js"></script>
<script>
twttr.events.bind('tweet' , function(event) {
  // do somethings here
alert("Tweet has been successfully posted");
});
</script>

twttr.events.bind 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


playing-slick-pg

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.

Thanks…:-)

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())
logger.error("................")

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="ch.qos.logback.classic.net.SMTPAppender">
		<smtpHost>smtp.gmail.com</smtpHost>
		<smtpPort>587</smtpPort>
		<STARTTLS>true</STARTTLS>
		<username>USERNAME</username>
		<password>PASSWORD</password>
		<asynchronousSending>false</asynchronousSending>
		<to>EMAIL-IDS</to>
		<from>NAME</from>
		<subject>ERROR: %logger{20} - %m</subject>
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%date %-5level %logger - %message%n</pattern>
		</layout>
	</appender>
	<root level="info">
		<appender-ref ref="EMAIL" />
	</root>

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="com.example.foo" level="debug">
		<appender-ref ref="CONSOLE" /
</logger>

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:-

  • ARRAY
  • 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 EXTENSION hstore;

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 https://github.com/tminglei/slick-pg , 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.

Selection_039

For complete example, please go here https://gist.github.com/ayushmishra2005/d382801e0cb2d0df9e7c

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