form demoinplaywithmysql

31
Mysql Ruchi Jindal Software Consultant Knoldus

Upload: knoldus-software-llp

Post on 11-May-2015

10.001 views

Category:

Technology


1 download

DESCRIPTION

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.

TRANSCRIPT

Page 1: Form demoinplaywithmysql

Design Forms: Play2.0 Scala Mysql

Ruchi Jindal Software Consultant

Knoldus

Page 2: Form demoinplaywithmysql

Create a new Project In playConnectivity with MysqlAdd Twitter BootstrapDesign Main TemplateDesign Index Template

– SignInForm– Models– Controllers– Routing

Design Signup Template – SignUpForm– Models– Controllers– Routing

Agenda

Page 3: Form demoinplaywithmysql

Create a new Project In play

Page 4: Form demoinplaywithmysql

Create a new Project In play

Page 5: Form demoinplaywithmysql

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

Page 6: Form demoinplaywithmysql

Application hierarchy would be like this

Page 7: Form demoinplaywithmysql

Connectivity With Mysql

Page 8: Form demoinplaywithmysql

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

Page 9: Form demoinplaywithmysql

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.Driverdb.default.url="jdbc:mysql://localhost/FORMDEMO?characterEncoding=UTF-8"db.default.user=rootdb.default.password=root

Step #6 Add mysql script in 1.sql

Page 10: Form demoinplaywithmysql

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;

Page 11: Form demoinplaywithmysql

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 ;

Page 12: Form demoinplaywithmysql

Add Twitter Bootstrap

Page 13: Form demoinplaywithmysql

Steps Required To Add twitter Bootstrap

Step #1 Download bootstrap.min.css from

http://twitter.github.com/bootstrap/

Step #2 Add bootstrap.min.css

public → stylesheets -> bootstrap.min.css from

Page 14: Form demoinplaywithmysql

Design Main template

Page 15: Form demoinplaywithmysql

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:

Page 16: Form demoinplaywithmysql

@(title: Html)(content: Html)<!DOCTYPE html><html> <head> <title>@title</title> <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/bootstrap.min.css")"> <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")"> <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")"> <script src="@routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script> <script src="@routes.Assets.at("javascripts/bootstrap-alert.js")" type="text/javascript"></script> </head> <header class="topbar"> <h1 class="fill"> <a href="/">Play 2.0 Form Demo &mdash; MySql</a> <a href="signout" style="float: right;"><input type="button" class="btn primary" value="Signout"></a> </h1> </header> <section id="main"> @if(Common.alert.alertType != ""){ <div class="alert-message @Common.alert.alertType"> <a class="close" data-dismiss="alert">×</a> <strong style="text-transform: capitalize;">@Common.alert.alertType ! </strong>@Common.alert.message </div> } @content <footer><a href="/">Back To Home Page</a></footer> </section></html>

Page 17: Form demoinplaywithmysql

Main Template View

Page 18: Form demoinplaywithmysql

Design index.html.scala template

Page 19: Form demoinplaywithmysql

Steps Required To Design Index Form

Step #1 add case class for employee in app->models->Models.scalacase 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 pagedef index = Action { Ok(views.html.index(signinForm, "Form Demo in Play2.0 With Mysql As Database")) }Step #4 set routesGET / controllers.Application.indexPOST /login controllers.Application.authenticateUser

Page 20: Form demoinplaywithmysql

@(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> } }

Page 21: Form demoinplaywithmysql

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

Page 22: Form demoinplaywithmysql

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) } } }) }

Page 23: Form demoinplaywithmysql
Page 24: Form demoinplaywithmysql

Design SignUp Form

Page 25: Form demoinplaywithmysql

Steps Required To Design SignUp Form

Step #1 Already Have case class for employee in app->models->Models.scalacase 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, ""))})

Page 26: Form demoinplaywithmysql

Step #3 redirect to SignUp pagedef siginUpForm = Action { val alert: Alert = new Alert("", "") Common.setAlert(alert) Ok(views.html.signUpForm(signupForm, "Sign Up Form")) }

Step #4 set routesPOST /signUp controllers.Application.createEmployee

Page 27: Form demoinplaywithmysql

@(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> } }

Page 28: Form demoinplaywithmysql

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() } }

Page 29: Form demoinplaywithmysql

/** * 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")) } }) }

Page 30: Form demoinplaywithmysql
Page 31: Form demoinplaywithmysql