Suggested Pages

Tuesday, May 26, 2015

JPA Example of Named Query

Contact.java



@NamedQueries(value = @NamedQuery(name = "findContactByMail", query = "SELECT c FROM Contact c WHERE c.mail= :mail AND c.location= :location"))
@Entity
@Table(name = "CONTACT")
public class Contact {

 @Id
 @Column(name = "ID")
 @GeneratedValue(strategy = GenerationType.AUTO)
 private Long id;

 @Column(name = "MAIL")
 private String mail;

 @Column(name = "LOCATION")
 private String location;

        ....
}

Client.java

   
   @PersistenceContext
   private EntityManager entityManager;


   public Contact findContactByMail(String mail, String location){

     TypedQuery findContactByMail = entityManager.createNamedQuery("findContactByMail",Contact.class);
     findContactByMail.setParameter("mail", mail);
     findContactByMail.setParameter("location", location);

       try {
            return findContactByMail.getSingleResult();
       } 
       catch (NoResultException e) {
            return null;
       }
    }
    ....
}

No comments :

Post a Comment

Suggested Pages