4

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

 3 years ago
source link: https://blog.knoldus.com/play-with-reactive-slick-a-simple-crud-application-in-play-framework-using-slick-3-0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

Reading Time: 2 minutes

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

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

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

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

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK