利用@NameQueries和@NameQuery注解,一旦定义,可以可以调用正如其他命名查询。
import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * Person entity. * * @author MyEclipse Persistence Tools */ @Entity @Table(name = "person") @NamedQueries( { @NamedQuery(name = "person.query", query = "from Person p where p.id=? "), @NamedQuery(name = "person.query1", query = "from Person p where p.id=? ") }) public class Person implements java.io.Serializable { // Fields /** * serialVersionUID */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; private String source; private Integer sn;
public static void main(String[] args) { Session session = HibernateSessionFactory.getSession(); Transaction t = session.beginTransaction(); Person p = (Person)session.getNamedQuery("person.query1").setInteger(0,1).list().get(0) ; System.out.println(p.getName()); t.commit(); session.close(); }