无查询获取reference
child = new Child();
child.SetName("Henry");
Parent parent = em.getReference(Parent.class, parentId); //no query to the DB
child.setParent(parent);
em.persist(child);
重新获取对象实例及其相关对象
em.persist(cat);
em.flush(); // force the SQL insert and triggers to run
em.refresh(cat); //re-read the state (after the trigger executes)
当确信只有一个对象会被返回时可用
getSingleResult()
投影,一次返回多个对象
Iterator kittensAndMothers = sess.createQuery(
"select kitten, mother from Cat kitten join kitten.mother mother")
.getResultList()
.iterator();
while ( kittensAndMothers.hasNext() ) {
Object[] tuple = (Object[]) kittensAndMothers.next();
Cat kitten = tuple[0];
Cat mother = tuple[1];
....
}
Scalar results
Iterator results = em.createQuery(
"select cat.color, min(cat.birthdate), count(cat) from Cat cat " +
"group by cat.color")
.getResultList()
.iterator();
while ( results.hasNext() ) {
Object[] row = results.next();
Color type = (Color) row[0];
Date oldest = (Date) row[1];
Integer count = (Integer) row[2];
.....
}
分页
Query q = em.createQuery("select cat from DomesticCat cat");
q.setFirstResult(20);
q.setMaxResults(10);
List cats = q.getResultList(); //return cats from the 20th position to 29th
预先定义的查询
@javax.persistence.NamedQuery(name="eg.DomesticCat.by.name.and.minimum.weight", query="select cat from eg.DomesticCat as cat where cat.name = ?1 and cat.weight > ?2")
Query q = em.createNamedQuery("eg.DomesticCat.by.name.and.minimum.weight");
q.setString(1, name);
q.setInt(2, minWeight);
List cats = q.getResultList();
使用merge的情景
- 应用load一个object在第一个em
- 该对象被传递到表现层
- 该对象的一些属性被修改
- 然后返回到业务逻辑导
- 此时可用第二个em调用merge()
merge的行为
- 如果该对象有与持久层中相同的ID,则拷贝所有属性到受管对象
- 如果当前没有受管对象,则数据库中load一个或者创建一个受管对象
- 返回受管对象
- 作为参数的那个对象不会变为一个受管对象,依然保持游离态
merge不象hibernate的saveOrUpdate, 对象不会与持久层上下文绑定,但是一个受管对象会被merge返回
本文介绍了使用ORM进行数据库操作的最佳实践,包括如何避免不必要的数据库查询、如何重新加载对象状态、如何进行分页查询以及如何利用预定义查询提高效率。此外还讨论了不同场景下使用merge方法的注意事项。
97

被折叠的 条评论
为什么被折叠?



