1.JPA持久化
当 play找到至少一个注释了@javax.persistence.Entity标识的类时,play 将自动启动 hibernate
实体管理器。
Query query = JPA.em().createQuery("select * fromArticle");
List<Article> articles =query.getResultList();
render(articles);
2.事物管理
play 会自动管理事务。当http 请求到达,play 就会为每个 http 请求启动一个事务。当 http
response 发送的时候,就会把事务提交。如果代码抛出异常,事务将会自动回滚。
如果在控制器里用@play.db.jpa.Transactional(readOnly=true)注释了控制器的某个方法, 那么这个事务是只读的。
如果不想让 play启动事务,可以使用以下注释@play.db.jpa.NoTransaction。
如下面的 Post模型对象:
@Entity
public class Post extends Model {
public String title;
public String content;
public Date postDate;
@ManyToOne
public Author author;
@OneToMany
public List<comment> comments;
}
play.db.jpa.Model 类自动提供了一个自增长的 Long id域。采用自增长的 Long id 主键对 jpa 模型来说是个好主意。
你的 JPA 实体也可以继承 play.db.jpa.GenericModel,
如果不打算使用 Long类型的 id 作为主键,就必须这样做。
比如,下面是一个非常简单的 User实体类。它的 id 是 UUID, name 和 mail 属性都是非空值,
我们使用 play验证进行强制检测:
@Entity
public class User extends GenericModel {
@Id
@GeneratedValue(generator ="system-uuid")
@GenericGenerator(name ="system-uuid", strategy = "uuid")
public String id;
@Required public String name;
@Required
@MaxSize(value=255, message =“email.maxsize”)
@play.data.validation.Email3.查询语句
3.1.Finding对象
Find by Id
Post aPost =Post.findById(5L);
Find all
List<Post> posts =Post.findAll();
这是获取所有 posts 对象最简单的方式,类似的应用还有:
List<Post> posts =Post.all().fetch();
下面对结果进行分页:
List<Post> posts =Post.all().from(50).fetch(100);
3.2.JPQL 查询
Post.find("select p from Post p, Commentc " +
"where c.post = p and c.subject like ?", "%hop%");
或仅查询某部分:
Post.find("title","My first post").fetch();
Post.find("title like ?","%hello%").fetch();
Post.find("author is null").fetch();
也可仅有 order by 语句:
Post.find("order by postDate desc").fetch();