-
Notifications
You must be signed in to change notification settings - Fork 0
The Model Layer
pramode edited this page Jun 28, 2011
·
5 revisions
Create a model:
package models;
import java.util.*;
import javax.persistence.*;
import play.db.jpa.*;
import play.data.validation.*;
@Entity
public class Client extends Model {
@Required(message="Name is required")
public String name;
@Required
@Min(10)
public int age;
}
Here are the controller functions:
public static void listclients() {
List <Client> client_list = Client.findAll();
render(client_list);
}
public static void addclient(Client c) {
c.save();
listclients();
}
Here are the URL's:
GET /addclient Application.addclient
GET /listclients Application.listclients
And here is the template:
#{extends 'layout1.html' /}
#{set title:'Testing decoration' /}
<p>
<ul>
#{list items:client_list, as:'client'}
<li>${client.name}, ${client.age}</li>
#{/list}
</ul>
Instead of Client.findAll(), we can use:
Client.all.fetch()
Client.all.fetch(100); // max 100 entries
Client.all.from(50).fetch(100); // fetch 100 entries starting from 50th.
Searching for a client by name:
public static void searchclient(String name) {
List <Client> client_list;
client_list = Client.find("byName", name).fetch();
render("Application/listclients.html", client_list);
}
Pattern matching:
client_list = Client.find("byNameLike", "%foo%").fetch();
Another example:
client_list = Client.find("byNameLikeAndAge", "%op", 67)
find all clients whose name contains a substring "op" and age is 67
finds out all names containing substring foo.
More info in the official documentation.
The above are "simplified queries".
So called "JPL queries" are more expressive:
client_list = Client.find("select p from Client p where age > ?", 100).fetch();
client_list = Client.find("order by age desc").fetch();
Read the official docs