在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對象了。