It is easy to use the CreateQuery method of the Entitymanager object in EJB3 to perform JPQL (similar to hibernate in HQL). However, when using the CreateQuery method to process JPQL, the system needs to analyze JPQL during each execution of JPQL, which reduces the performance of the system in some degree. To do this, EJB3 provides the concept of named queries. Named queries have some types of stored procedures in the database that have been compiled and processed during the commit process. Therefore, the efficiency of implementation should be higher.
We can use @namedquery annotations to define named queries. This annotation can be placed above any entity bean. For ease of administration, however, it is best to put it above the relevant entity bean. As shown in the following code:
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") publi
C 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 = @JoinCo Lumn (name = "address_id", referencedcolumnname = "id")) public collection<address> getaddresses () {return a
ddresses;
public void setaddresses (collection<address> addresses) {this.addresses = addresses; @OneToMany (Mappedby = "Customer", cascade = cascadetype.all) public collection<order> getorders () {retur
n Orders;
public void Setorders (collection<order> orders) {this.orders = orders;
@Id @GeneratedValue (strategy = generationtype.identity) public int getId () {return Id;
The public void setId (int id) {this.id = ID; Public String GetName () {return Name
public void SetName (String name) {this.name = name; }
}
Named queries in your code use named parameters. We can use the following code to execute the JPQL:
Private Customer querycustomer (int id)
{return
(Customer) em.createnamedquery ("Myquery"). Setparameter ("id")
. Getsingleresult ();
}
Call Querycustomer in the session bean to get the corresponding customer object from the named query.