Categorias
Java MySQL Play

facilidade do Play 2 em fazer CRUD com MySQL

Todo começo de projeto sempre tem a parte chata de cadastro.

Quando se gasta tempo precioso fazendo tela de CRUD que só o administrador (você) vai usar, isso passa de chato para insuportável!

quesaco

Felizmente alguns frameworks tem alguma facilidade desenvolvida oficialmente ou não.

No caso do Play Framework, que tem como um de seus destaques a facilidade de uso, não poderia ser diferente. Entretanto, o facilitador de CRUD do Play não é oficial, é um dos interessantes plugins do site http://www.playmodules.net/ , o play2-crud .

Vou usar uma tabela bem simples no MySQL, e vou mostrar como alterar apenas 5 arquivos e ter uma aplicação nova com CRUD funcionando.

Começamos criando a aplicação:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fb@cascao ~/workspace-play > play new play2-crud-mysql
_
_ __ | | __ _ _ _
| '_ \| |/ _' | || |
| __/|_|\____|\__ /
|_| |__/
play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_51), http://www.playframework.com
The new application will be created in /home/fb/workspace-play/play2-crud-mysql
What is the application name? [play2-crud-mysql]
>
Which template do you want to use for this new application?
1 - Create a simple Scala application
2 - Create a simple Java application
> 2
OK, application play2-crud-mysql is created.
Have fun!
fb@cascao ~/workspace-play >
fb@cascao ~/workspace-play > play new play2-crud-mysql _ _ __ | | __ _ _ _ | '_ \| |/ _' | || | | __/|_|\____|\__ / |_| |__/ play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_51), http://www.playframework.com The new application will be created in /home/fb/workspace-play/play2-crud-mysql What is the application name? [play2-crud-mysql] > Which template do you want to use for this new application? 1 - Create a simple Scala application 2 - Create a simple Java application > 2 OK, application play2-crud-mysql is created. Have fun! fb@cascao ~/workspace-play >
fb@cascao ~/workspace-play > play new play2-crud-mysql
       _
 _ __ | | __ _ _  _
| '_ \| |/ _' | || |
|  __/|_|\____|\__ /
|_|            |__/

play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_51), http://www.playframework.com

The new application will be created in /home/fb/workspace-play/play2-crud-mysql

What is the application name? [play2-crud-mysql]
> 

Which template do you want to use for this new application? 

  1             - Create a simple Scala application
  2             - Create a simple Java application

> 2
OK, application play2-crud-mysql is created.

Have fun!

fb@cascao ~/workspace-play >

Arquivo 1 – play2-crud-mysql\build.sbt – adicionamos as dependências do MySQL e do plugin play2-crud

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
name := "play2-crud-mysql"
version := "1.0-SNAPSHOT"
libraryDependencies ++= Seq(
javaJdbc,
javaEbean,
cache,
"mysql" % "mysql-connector-java" % "5.1.18",
"play2-crud" % "play2-crud_2.10" % "0.7.3-SNAPSHOT" exclude("com.typesafe.play", "play-cache_2.10")
)
resolvers += "hakandilek release" at "http://hakandilek.github.com/maven-repo/releases/"
resolvers += "hakandilek snapshots" at "http://hakandilek.github.com/maven-repo/snapshots/"
play.Project.playJavaSettings
name := "play2-crud-mysql" version := "1.0-SNAPSHOT" libraryDependencies ++= Seq( javaJdbc, javaEbean, cache, "mysql" % "mysql-connector-java" % "5.1.18", "play2-crud" % "play2-crud_2.10" % "0.7.3-SNAPSHOT" exclude("com.typesafe.play", "play-cache_2.10") ) resolvers += "hakandilek release" at "http://hakandilek.github.com/maven-repo/releases/" resolvers += "hakandilek snapshots" at "http://hakandilek.github.com/maven-repo/snapshots/" play.Project.playJavaSettings
name := "play2-crud-mysql"

version := "1.0-SNAPSHOT"

libraryDependencies ++= Seq(
  javaJdbc,
  javaEbean,
  cache,
  "mysql" % "mysql-connector-java" % "5.1.18",
  "play2-crud" % "play2-crud_2.10" % "0.7.3-SNAPSHOT" exclude("com.typesafe.play", "play-cache_2.10")
)     

resolvers += "hakandilek release" at "http://hakandilek.github.com/maven-repo/releases/"

resolvers += "hakandilek snapshots" at "http://hakandilek.github.com/maven-repo/snapshots/"

play.Project.playJavaSettings

Depois de adicionadas as dependências, vamos configurar o Eclipse:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fb@cascao ~/workspace-play/play2-crud-mysql > play
[info] Loading project definition from /home/fb/workspace-play/play2-crud-mysql/project
[info] Set current project to play2-crud-mysql (in build file:/home/fb/workspace-play/play2-crud-mysql/)
_
_ __ | | __ _ _ _
| '_ \| |/ _' | || |
| __/|_|\____|\__ /
|_| |__/
play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_51), http://www.playframework.com
> Type "help play" or "license" for more information.
> Type "exit" or use Ctrl+D to leave this console.
[play2-crud-mysql] $ eclipse with-source=true
[info] About to create Eclipse project files for your project(s).
[info] Updating {file:/home/fb/workspace-play/play2-crud-mysql/}play2-crud-mysql...
[info] Resolving mysql#mysql-connector-java;5.1.18 ...
[info] Successfully created Eclipse project files for project(s):
[info] play2-crud-mysql
fb@cascao ~/workspace-play/play2-crud-mysql > play [info] Loading project definition from /home/fb/workspace-play/play2-crud-mysql/project [info] Set current project to play2-crud-mysql (in build file:/home/fb/workspace-play/play2-crud-mysql/) _ _ __ | | __ _ _ _ | '_ \| |/ _' | || | | __/|_|\____|\__ / |_| |__/ play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_51), http://www.playframework.com > Type "help play" or "license" for more information. > Type "exit" or use Ctrl+D to leave this console. [play2-crud-mysql] $ eclipse with-source=true [info] About to create Eclipse project files for your project(s). [info] Updating {file:/home/fb/workspace-play/play2-crud-mysql/}play2-crud-mysql... [info] Resolving mysql#mysql-connector-java;5.1.18 ... [info] Successfully created Eclipse project files for project(s): [info] play2-crud-mysql
fb@cascao ~/workspace-play/play2-crud-mysql > play
[info] Loading project definition from /home/fb/workspace-play/play2-crud-mysql/project
[info] Set current project to play2-crud-mysql (in build file:/home/fb/workspace-play/play2-crud-mysql/)
       _
 _ __ | | __ _ _  _
| '_ \| |/ _' | || |
|  __/|_|\____|\__ /
|_|            |__/

play 2.2.2 built with Scala 2.10.3 (running Java 1.7.0_51), http://www.playframework.com

> Type "help play" or "license" for more information.
> Type "exit" or use Ctrl+D to leave this console.

[play2-crud-mysql] $ eclipse with-source=true
[info] About to create Eclipse project files for your project(s).
[info] Updating {file:/home/fb/workspace-play/play2-crud-mysql/}play2-crud-mysql...
[info] Resolving mysql#mysql-connector-java;5.1.18 ...
[info] Successfully created Eclipse project files for project(s):
[info] play2-crud-mysql

Agora podemos importar o nosso projeto pelo Eclipse, e trabalhar com ele.

Arquivo 2 – play2-crud-mysql\app\models\Seriado.java – dentro da package models , definimos o nosso domain Seriado:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package models;
import javax.persistence.*;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;
import play.utils.dao.BasicModel;
@Entity
public class Seriado extends Model implements BasicModel {
private static final long serialVersionUID = 2500768374252151706L;
@Id
private Long id;
@Basic
@Required
private String nome;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Long getKey() {
return id;
}
public void setKey(Long key) {
setId(key);
}
}
package models; import javax.persistence.*; import play.data.validation.Constraints.Required; import play.db.ebean.Model; import play.utils.dao.BasicModel; @Entity public class Seriado extends Model implements BasicModel { private static final long serialVersionUID = 2500768374252151706L; @Id private Long id; @Basic @Required private String nome; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Long getKey() { return id; } public void setKey(Long key) { setId(key); } }
package models;

import javax.persistence.*;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;
import play.utils.dao.BasicModel;

@Entity
public class Seriado extends Model implements BasicModel {

    private static final long serialVersionUID = 2500768374252151706L;

    @Id
    private Long id;

    @Basic
    @Required
    private String nome;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Long getKey() {
        return id;
    }

    public void setKey(Long key) {
        setId(key);
    }

}

Arquivo 3 – play2-crud-mysql\conf\application.conf – configurações de banco de dados MySQL e do Play2-CRUD :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#
# Play 2 CRUD para MySQL
# ~~~~~
# Secret key
application.secret="a^gBGEMapwMhdr/FY1NtsiG6`TGsbsT[]q:lZU:US
# The application languages
# ~~~~~
application.langs="en"
# Ajuste do Play2 CRUD
# ~~~~~
application.global=play.utils.crud.GlobalCRUDSettings
# Database configuration
# ~~~~~
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost/boaglio1"
db.default.user=boaglio1
db.default.password="boaglio1"
# Evolutions
# ~~~~~
evolutionplugin=enabled
# Ebean configuration
# ~~~~~
ebean.default="models.*"
# Logger
logger.root=ERROR
logger.play=INFO
logger.application=DEBUG
# # Play 2 CRUD para MySQL # ~~~~~ # Secret key application.secret="a^gBGEMapwMhdr/FY1NtsiG6`TGsbsT[]q:lZU:US # The application languages # ~~~~~ application.langs="en" # Ajuste do Play2 CRUD # ~~~~~ application.global=play.utils.crud.GlobalCRUDSettings # Database configuration # ~~~~~ db.default.driver=com.mysql.jdbc.Driver db.default.url="jdbc:mysql://localhost/boaglio1" db.default.user=boaglio1 db.default.password="boaglio1" # Evolutions # ~~~~~ evolutionplugin=enabled # Ebean configuration # ~~~~~ ebean.default="models.*" # Logger logger.root=ERROR logger.play=INFO logger.application=DEBUG
#
# Play 2 CRUD para MySQL
# ~~~~~

# Secret key
application.secret="a^gBGEMapwMhdr/FY1NtsiG6`TGsbsT[]q:lZU:US

# The application languages
# ~~~~~
application.langs="en"

# Ajuste do Play2 CRUD
# ~~~~~
application.global=play.utils.crud.GlobalCRUDSettings

# Database configuration
# ~~~~~
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost/boaglio1"
db.default.user=boaglio1
db.default.password="boaglio1"

# Evolutions
# ~~~~~
evolutionplugin=enabled

# Ebean configuration
# ~~~~~
ebean.default="models.*"

# Logger
logger.root=ERROR
logger.play=INFO
logger.application=DEBUG

Arquivo 4 – play2-crud-mysql\conf\routes.conf – adicionadas rotas do Play2-CRUD :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
GET /assets/*file controllers.Assets.at(path="/public", file)
# Rota do Play2 CRUD
-> /app play.crud.Routes
# Rota do Play2 CRUD - REST
-> /api play.rest.Routes
# Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # Home page GET / controllers.Application.index() GET /assets/*file controllers.Assets.at(path="/public", file) # Rota do Play2 CRUD -> /app play.crud.Routes # Rota do Play2 CRUD - REST -> /api play.rest.Routes
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
GET     /                           controllers.Application.index()
GET     /assets/*file               controllers.Assets.at(path="/public", file)

# Rota do Play2 CRUD
->     /app             play.crud.Routes

# Rota do Play2 CRUD - REST
->     /api             play.rest.Routes

Arquivo 5 – play2-crud-mysql\app\views\index.scala.html – página inicial auxiliar:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@(message: String)
@main("Play2 CRUD MySQL") {
<h2>Play2 CRUD MySQL <h2>
<a href="/app">Lista de tabelas para o CRUD</a>
<a href="/api">Lista de chamadas REST</a>
<a href="/api/Seriado/list">Lista de seriados em REST</a>
}
@(message: String) @main("Play2 CRUD MySQL") { <h2>Play2 CRUD MySQL <h2> <a href="/app">Lista de tabelas para o CRUD</a> <a href="/api">Lista de chamadas REST</a> <a href="/api/Seriado/list">Lista de seriados em REST</a> }
@(message: String)

@main("Play2 CRUD MySQL") {
  <h2>Play2 CRUD MySQL <h2>
  <a href="/app">Lista de tabelas para o CRUD</a>
  <a href="/api">Lista de chamadas REST</a>
  <a href="/api/Seriado/list">Lista de seriados em REST</a>
}

Nosso CRUD está pronto, vamos colocar para funcionar:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[play2-crud-mysql] $ run
--- (Running the application from SBT, auto-reloading is enabled) ---
[info] play - Listening for HTTP on /0.0.0.0:9000
(Server started, use Ctrl+D to stop and go back to the console...)
[info] play - database [default] connected at jdbc:mysql://localhost/boaglio1
[info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Double : play.utils.meta.convert.DoubleConverter@241ca5f1
[info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Integer : play.utils.meta.convert.IntegerConverter@54d283bc
[info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Long : play.utils.meta.convert.LongConverter@48c6d725
[info] play - Application started (Dev)
[play2-crud-mysql] $ run --- (Running the application from SBT, auto-reloading is enabled) --- [info] play - Listening for HTTP on /0.0.0.0:9000 (Server started, use Ctrl+D to stop and go back to the console...) [info] play - database [default] connected at jdbc:mysql://localhost/boaglio1 [info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Double : play.utils.meta.convert.DoubleConverter@241ca5f1 [info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Integer : play.utils.meta.convert.IntegerConverter@54d283bc [info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Long : play.utils.meta.convert.LongConverter@48c6d725 [info] play - Application started (Dev)
[play2-crud-mysql] $ run

--- (Running the application from SBT, auto-reloading is enabled) ---

[info] play - Listening for HTTP on /0.0.0.0:9000

(Server started, use Ctrl+D to stop and go back to the console...)

[info] play - database [default] connected at jdbc:mysql://localhost/boaglio1
[info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Double : play.utils.meta.convert.DoubleConverter@241ca5f1
[info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Integer : play.utils.meta.convert.IntegerConverter@54d283bc
[info] p.u.m.c.ClasspathScanningConverterRegistry - Converter:class java.lang.Long : play.utils.meta.convert.LongConverter@48c6d725
[info] play - Application started (Dev)

Acessando http://localhost:9000/ temos a página informando que a tabela de seriados não existe:

play-evolution

Depois de clicar em apply this script now!, será criada a tabela no MySQL e exibida a tela inicial:

play-crud1

Na primeira opção o plugin automaticamente lista todos os domains (no nosso caso temos apenas um):

play-crud2

Clicando em create, vamos para a tela para cadastrar um novo seriado:

play-novo-seriado

Depois de cadastrado, o registro é exibido em uma data table:

play-novo-seriado2

Toda a estrutura de CRUD está pronta, adicionando mais uma classe de domínio na package models, ela automaticamente já entra na tela inicial para cadastrar, e isso sem nem reiniciar o servidor.

Além dessa facilidade, o plugin play2-crud ainda oferece as operações de CRUD via REST, algo que é muito interessante fazer, por exemplo, via Android/iOS.

Depois de popular a tabela de seriados com esse script SQL, temos o exemplo no browser:

play REST

Todos os fontes aqui estão nesse projeto do GitHub: https://github.com/boaglio/play2-crud-mysql .

Essa é uma das várias facilidades do Play Framework , no artigo anterior comentei do integração com o MongoDB e também gostei tanto de usar Play que escrevi um livro sobre o assunto.

Fernando Boaglio, para a comunidade