在EJB3中可以使用EntityManager对象的createQuery方法来执行JPQL(类似于Hibernate中的HQL),这非常简单。但使用createQuery方法处理JPQL时,在每次执行JPQL的过程中系统都需要对JPQL进行分析,这在一定程度上降低了系统运行时的性能。为此,EJB3提供了命名查询的概念。命名查询有些类型于数据库中的存储过程,在提交的过程中就已经被编译处理了。因此,在执行效率上要高一些。
我们可以使用@NamedQuery注释来定义命名查询。这个注释可以放在任何一个实体Bean的上方。但为了便于管理,最好放在相关的实体Bean的上方。如下面的代码所示:
- package entity;
- import java.util.Collection;
- import javax.persistence.CascadeType;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.JoinTable;
- import javax.persistence.ManyToMany;
- import javax.persistence.NamedQuery;
- import javax.persistence.OneToMany;
- import javax.persistence.OneToOne;
- import javax.persistence.PrimaryKeyJoinColumn;
- import javax.persistence.Table;
- @Entity
- @Table(name = "t_customers")
- @NamedQuery(name="MyQuery",query="select c from Customer c where id=:id")
- public class Customer
- {
- private int id;
- private String name;
- private Referee referee;
- private Collection<Order> orders;
- private Collection<Address> addresses;
- @OneToOne(cascade = CascadeType.ALL)
- @PrimaryKeyJoinColumn
- public Referee getReferee()
- {
- return referee;
- }
- public void setReferee(Referee referee)
- {
- this.referee = referee;
- }
- @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
- @JoinTable(name = "t_customers_addresses",
- joinColumns = @JoinColumn(name = "customer_id", referencedColumnName = "id"),
- inverseJoinColumns = @JoinColumn(name = "address_id", referencedColumnName = "id"))
- public Collection<Address> getAddresses()
- {
- return addresses;
- }
- public void setAddresses(Collection<Address> addresses)
- {
- this.addresses = addresses;
- }
- @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
- public Collection<Order> getOrders()
- {
- return orders;
- }
- public void setOrders(Collection<Order> orders)
- {
- this.orders = orders;
- }
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- public int getId()
- {
- return id;
- }
- public void setId(int id)
- {
- this.id = id;
- }
- public String getName()
- {
- return name;
- }
- public void setName(String name)
- {
- this.name = name;
- }
- }
代码中的命名查询使用了命名参数。我们可以使用下面的代码来执行该JPQL:
- private Customer queryCustomer(int id)
- {
- return (Customer) em.createNamedQuery("MyQuery").setParameter("id", 23)
- .getSingleResult();
- }
在Session Bean中调用queryCustomer就可以通过命名查询获得相应的Customer对象了。
【编辑推荐】