This presentation emphasis on How to connect a Play Application with Mysql as database in Scala.Play includes a simple data access layer called Anorm that uses plain SQL to interact with the database and provides an API to parse and transform the resulting datasets.
5. Create a new Project In play
$:~/Desktop/knolx $ play new FormDemoInPlay
Select Application name
Select application Template
Application would be created with name FormDemoInPlay
$:~/Desktop/knolx $ cd FormDemoInPlay/
To open project in eclipse
$:~/Desktop/knolx /FormDemoInPlay$ play eclipsify
8. Steps Required for Mysql Connectivity
Step #1 create new schema
mysql> create database FORMDEMO
Step #2 add mysql connector dependency in Build.scala
"mysql" % "mysql-connector-java" % "5.1.18"
Step #3 create default directory
conf → evolutions → default
9. Step #4 Add 1.sql
conf → evolutions → default → 1.sql
Step #5 Add mysql driver and default url in application.conf
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost/FORMDEMO?characterEncoding=UTF-
8"
db.default.user=root
db.default.password=root
Step #6 Add mysql script in 1.sql
10. use `FORMDEMO`;
DROP TABLE if exists EMPLOYEE_DETAIL;
DROP TABLE if exists EMPLOYEE;
CREATE TABLE `FORMDEMO`.`EMPLOYEE` (
`EMPLOYEE_ID` INT NOT NULL AUTO_INCREMENT ,
`EMAIL` VARCHAR(45) NOT NULL ,
`PASSWORD` VARCHAR(100) NOT NULL ,
PRIMARY KEY (`EMPLOYEE_ID`) )
ENGINE = InnoDB;
11. CREATE TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` (
`EMPLOYEE_DETAIL_ID` INT NOT NULL AUTO_INCREMENT ,
`EMPLOYEE_ID` INT NOT NULL ,
`NAME` VARCHAR(45) NOT NULL ,
`DESIGNATION` VARCHAR(45) NOT NULL ,
`ADDRESS` VARCHAR(100) NOT NULL ,
`CONTACT_NO` VARCHAR(20) NOT NULL ,
PRIMARY KEY (`EMPLOYEE_DETAIL_ID`) ,
INDEX `fk_EMPLOYEE_DETAIL_1_idx` (`EMPLOYEE_ID` ASC) ,
CONSTRAINT `fk_EMPLOYEE_DETAIL_1`
FOREIGN KEY (`EMPLOYEE_ID` )
REFERENCES `FORMDEMO`.`EMPLOYEE` (`EMPLOYEE_ID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
ALTER TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` CHANGE COLUMN
`NAME` `NAME` VARCHAR(100) NOT NULL ;
ALTER TABLE `FORMDEMO`.`EMPLOYEE_DETAIL` CHANGE COLUMN
`NAME` `NAME` VARCHAR(80) NOT NULL ;
15. Steps Required To Desin Main template
Step #1 Add Title and Content
@(title: Html)(content: Html)
Step #2 Set Header,Navigation,Content,Footer
Decide the page layout
Step #3 Add CSS and Javascripts and add Content
Full code to design main template is as follows:
19. Steps Required To Design Index Form
Step #1 add case class for employee in app->models->Models.scala
case class Employee(id: Pk[Int] = NotAssigned, email: String, password: String)
Step #2 add play.api.data.Form For SignIn in Application Controller
val signinForm = Form(
Forms.mapping(
"id" -> ignored(NotAssigned: Pk[Int]),
"email" -> email,
"password" -> nonEmptyText(minLength = 6))(Employee.apply)(Employee.unapply))
Step #3 redirect to index page
def index = Action {
Ok(views.html.index(signinForm, "Form Demo in Play2.0 With Mysql As Database"))
}
Step #4 set routes
GET / controllers.Application.index
POST /login controllers.Application.authenticateUser
20. @(signinForm:Form[Employee],message:String)
@import helper._
@import helper.twitterBootstrap._
@title = {
Form Demo in Play2.0 With Mysql As Database
}
@main(title) {
@helper.form(action = routes.Application.authenticateUser) {
<fieldset>
<legend>@message</legend>
@inputText(
signinForm("email"), '_label -> "Email ",
'_help -> "Enter a valid email address."
)
@inputPassword(
signinForm("password"),
'_label -> "Password",
'_help -> "A password must be at least 6 characters. "
)
</fieldset>
<div class="actions">
<input type="submit" class="btn primary" value="Log in ">
Or
<small><a href="@routes.Application.siginUpForm">Sign Up </a></small>
</div>
}
}
21. Design Model For Employee Entity
object Employee {
/**
* Parse a Employee from a ResultSet
*/
val simple = {
get[Pk[Int]]("employee.employee_id") ~
get[String]("employee.email") ~
get[String]("employee.password") map {
case id ~ email ~ password => Employee(id, email, password)
}
}
/**
* Find Employee Via Email and password
*/
def authenticate(employee: Employee) = {
DB.withConnection { implicit connection =>
val employeeFound = SQL(
"""
select * from EMPLOYEE
where EMAIL = {email} and PASSWORD= {password}
""").on(
'email -> employee.email,
'password -> employee.password).as(Employee.simple.singleOpt)
employeeFound
}
}
}
22. Sign In authenticate controller in Application.scala
/**
* Authenticate User For Login
*/
def authenticateUser = Action { implicit request =>
val alert: Alert = new Alert("", "")
Common.setAlert(alert)
signinForm.bindFromRequest.fold(
errors => BadRequest(views.html.index(errors, "There is some
error")),
employee => {
val employeeOpt = Employee.authenticate(employee)
employeeOpt match {
case None =>
Ok("Invalid Credentials")
case Some(authemployee: Employee) =>
val userSession = request.session + ("userId" ->
authemployee.id.toString)
Ok("Valid User").withSession(userSession)
}
}
})
}
25. Steps Required To Design SignUp Form
Step #1 Already Have case class for employee in app->models->Models.scala
case class Employee(id: Pk[Int] = NotAssigned, email: String, password: String)
Step #2 add play.api.data.Form For SignUp in Application Controller
val signupForm: Form[Employee] = Form(
mapping(
"email" -> email,
"password" -> tuple(
"main" -> text(minLength = 6),
"confirm" -> text).verifying(
// Add an additional constraint: both passwords must match
"Passwords don't match", passwords => passwords._1 == passwords._2)) {
// Binding: Create a User from the mapping result (ignore the second password and the accept
field)
(email, passwords) => Employee(NotAssigned, email, passwords._1)
}{
// Unbinding: Create the mapping values from an existing User value
user => Some(user.email, (user.password, ""))})
26. Step #3 redirect to SignUp page
def siginUpForm = Action {
val alert: Alert = new Alert("", "")
Common.setAlert(alert)
Ok(views.html.signUpForm(signupForm, "Sign Up Form"))
}
Step #4 set routes
POST /signUp controllers.Application.createEmployee
27. @(signupForm: Form[Employee],message:String)
@import helper._
@import helper.twitterBootstrap._
@title = {
Sign Up Form in Play2.0
}
@main(title) {
@helper.form(action = routes.Application.createEmployee) {
<fieldset>
<legend>@message</legend>
@inputText(
signupForm("email"), '_label -> "Email",
'_help -> "Enter a valid email address."
)
@inputPassword(
signupForm("password.main"),
'_label -> "Password",
'_help -> "A password must be at least 6 characters. "
)
@inputPassword(
signupForm("password.confirm"),
'_label -> "Repeat password",
'_help -> "Please repeat your password again.",
'_error -> signupForm.error("password")
)
</fieldset>
<div class="actions">
<input type="submit" class="btn primary" value="Sign Up">
</div>
}
}
28. Design Model For To Register A new User
/**
* Register a new employee.
*
* @param employee The computer values.
*/
def insert(employee: Employee): Int = {
DB.withConnection { implicit connection =>
SQL(
"""
insert into EMPLOYEE(EMAIL,PASSWORD) values (
{email}, {password}
)
""").on(
'email -> employee.email,
'password -> employee.password).executeUpdate()
}
}
29. /**
* Register a new Employee
*/
def createEmployee = Action { implicit request =>
signupForm.bindFromRequest.fold(
errors => BadRequest(views.html.signUpForm(errors, "There is
some error")),
employee => {
Employee.findByEmployeeEmail(employee.email).isEmpty match {
case true =>
Employee.insert(employee)
val employee_Id = Employee.findMaxEmployeeId
val userSession = request.session + ("userId" ->
employee_Id.toString)
Ok("Employee Registered").withSession(userSession)
case false =>
val emailExistForm =
Application.signupForm.fill(Employee(NotAssigned, employee.email,
""))
Ok(views.html.signUpForm(emailExistForm, "Email Id
Already Exist"))
}
})
}