无查询获取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的情景
merge的行为
merge不象hibernate的saveOrUpdate, 对象不会与持久层上下文绑定,但是一个受管对象会被merge返回