JPA Support
Play provides a set of very useful helpers to simplify the management of your JPA entities.
Note that you can still go back to the plain JPA API whenever you want.
Starting the JPA entity manager
Play will automatically start the Hibernate entity manager when it finds one or more classes annotated with the @javax.persistence.Entity annotation. However, make sure that you have correctly configured a JDBC datasource or it will fail.
Obtaining the JPA entity manager
When the JPA entity manager is started you can get it from the application code, using the JPA helper. For example:
public static index() {
Query query = JPA.em().createQuery("select * from Article");
List<Article> articles = query.getResultList();
render(articles);
}
Transactions management
Play will automatically manage transactions for you. It will start a transaction for each HTTP request and commit it when the HTTP response is sent. If your code throws an exception, the transaction will be automatically rollbacked.
If you need to force the rollback of the transaction from the application code, you can use the JPA.setRollbackOnly() method.
The play.db.jpa.Model support class
This is the main helper class for JPA. If you make one of your JPA entity extends the play.db.jpa.Model class, it will give you a lot of helper methods to simplify the JPA access.
For example, look at this Post model object:
@Entity
public class Post extends Model {
public String title;
public String content;
public Date postDate;
@ManyToOne
public Author author;
@OneToMany
public List<Comment> comments;
}
The play.db.jpa.Model class automatically provides a autogenerated Long id field. We think that it’s generally a good idea to keep an auto-generated Long id as primary key for JPA models (the technical primary key) and manage your functional primary key using another field.
Note that we have used the fact that play automatically consider public members of the Post class as properties. So we don’t need to write all setter/getter methods for this object.
Finding objects
The play.db.jpa.Model gives you several ways to find data. For example:
Find by ID
The simplest way to find an object.
Post aPost = Post.findById(5L);
Find all
List<Post> posts = Post.findAll();
This is the simplest way to retrieve all posts, but you can do the same using:
List<Post> posts = Post.all().fetch();
This allows you to paginate results:
List<Post> posts = Post.all().fetch(100); // 100 max posts
or even,
List<Post> posts = Post.all().from(50).fetch(100); // 100 max posts start at 50
Find using a simplified query
That allow you to create very expressive finders, but will only work for simple queries.
Post.find("byTitle", "My first post").fetch();
Post.find("byTitleLike", "%hello%").fetch();
Post.find("byAuthorIsNull").fetch();
Post.find("byTitleLikeAndAuthor", "%hello%", connectedUser).fetch();
Find using a JPQL query
You can use a JPQL query:
Post.find(
"select p from Post p, Comment c where c.post = p and c.subject like ?", "%hop%"
);
or even a part of:
Post.find("title", "My first post").fetch();
Post.find("title like ?", "%hello%").fetch();
Post.find("author is null").fetch();
Post.find("title like % and author is null", "%hello%").fetch();
Post.find("title like % and author is null order by postDate", "%hello%").fetch();
You can even specify only the order by statement:
Post.find("order by postDate desc").fetch();
Counting objects
You can easily count objects.
long postCount = Post.count();
Or even count using a query:
long userPostCount = Post.count("author = ?", connectedUser);
Explicit save
Hibernate maintains a cache of Objects that have been queried from the database. These Objects are referred to as persistent Objects as long as the EntityManager that was used to fetch them is still active. That means that any changes to these Objects within the bounds of a transaction are automatically persisted when the transaction is committed. In standard JPA, these updates are implicit within the boundary of the transaction; you don’t have to explicitly call any method to persist the values.
The main downside is that we must manage all of our Objects manually. Instead of telling the EntityManager to update an Object (which would be far
more intuitive), we must tell the EntityManager which Objects NOT to update. We do this by calling refresh(), which essentially rolls back
a single entity. We do this just prior to calling commit on the transaction or when we realize the Object shouldn’t be updated.
Here is a common use case, when editing a persistent object after a form submit :
public static void save(Long id) {
User user = User.findById(id);
user.edit(params);
validation.valid(user);
if(validation.hasErrors()) {
// Here we have to explicitly discard the user modifications...
user.refresh();
edit(id);
}
show(id);
}
From what I’ve seen, most developers are not aware of this, and forget to discard the object state in case of errors, assuming that the object will not be saved without an explicit call to save().
So that’s exactly what we’ve changed in play. All the persistent objects extending the JPASupport/JPAModel will not be saved without an explicit call to the save() method. So you can actually rewrite the previous code as:
public static void save(Long id) {
User user = User.findById(id);
user.edit(params);
validation.valid(user);
if(validation.hasErrors()) {
edit(id);
}
user.save();
show(id);
}
This is far more intuitive. Moreover since it could be tedious to call explicitly save() on a large object graph, the save() call is automatically cascaded to the relationships annotated with the cascade=CascadeType.ALL attribute.
More about generic typing problems
The play.db.jpa.Model defines a set of generic methods. These generic methods use a type parameter to specify the return type of the method. When using those methods, the concrete type to be used as return value is derived from the invocation context using type inference.
For example, the findAll method is defined as:
<T> List<T> findAll();
And you use it as:
List<Post> posts = Post.findAll();
Here the Java compiler resolves the actual type of T using the fact that you assign the method result to a List<Post>. So T is resolved as a Post type.
Unfortunately, this doesn’t work if the return value of the generic method is directly used as a parameter for another method invocation or used in a loop. So the following code fails with a compiler error saying “Type mismatch: cannot convert from element type Object to Post”:
for(Post p : Post.findAll()) {
p.delete();
}
Of course you can resolve this issue using a temporary local variable, as:
List<Post> posts = Post.findAll(); // type inference works here!
for(Post p : posts) {
p.delete();
}
But wait, there is a better way. You can use a practical but rather unknown feature of the Java language, which makes the code shorter while more readable at the same time:
for(Post p : Post.<Post>findAll()) {
p.delete();
}