21 Haziran 2018 Perşembe

JPA @NamedQueries Anotasyonu

Giriş
Şu satırı dahil ederiz.
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
Parametreler :abc şeklinde yazılır.

Örnek
Parametresiz şöyle yaparız.
@NamedQueries({ 
  @NamedQuery(name = "father.findAll", query = "SELECT f FROM Father f") 
})
Örnek
Tek parametre kullanarak şöyle yaparız.
@NamedQueries({
  @NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"), 
  @NamedQuery(name = "Person.findById", query = "SELECT p FROM Person p 
    WHERE p.id = :id")
, @NamedQuery(name = "Person.findByName", query = "SELECT p FROM 
    Person p WHERE p.name = :person_name")
, @NamedQuery(name = "Person.findByLastname", query = "SELECT p FROM 
    Person p WHERE p.lastname = :lastname")
, @NamedQuery(name = "Person.findByEmail", query = "SELECT p 
    FROM Person p WHERE p.email = :email")
, @NamedQuery(name = "Person.findByPhone", query = "SELECT p 
   FROM Person p WHERE p.phone = :phone")})
Örnek
İki parametre kullanarak şöyle yaparız.
@NamedQueries(  
  {  
    @NamedQuery(  
      name = "validateUserQuery",  
      query = "from Login l where l.userName =:userName AND
              l.password =:userPassword" 
    )  
  }  
)  

@Entity
@Table(name="login")
public class Login {

 
  @Basic
  private String userName;

  @Basic
  private String password;

  ...
   
}
Örnek
3 parametre kullanarak şöyle yaparız.
@Entity
@Table(name = "expanditure")
@XmlRootElement
@NamedQueries({
  @NamedQuery(name = "Expanditure.findAll",
    query = "SELECT e FROM Expanditure e"),
  @NamedQuery(name = "Expanditure.findById",
    query = "SELECT e FROM Expanditure e WHERE e.id = :id"),
  @NamedQuery(name = "Expanditure.findByMonthAndYear",
    query = "SELECT e FROM Expanditure e WHERE e.year = :year and e.month = :month ")
})
public class Expanditure implements Serializable {
  ...
}
Çağırma - Hibernate
Çağırmak için şöyle yaparız.
String userName = ...;
String userPassword = ...;

return (Login) getSession().getNamedQuery("validateUserQuery")
                .setString("userName", userName)
                .setString("userPassword", userPassword).uniqueResult();
Çağırma - JPA
em.createNamedQuery() kullanılır. Örnek ver.



Hiç yorum yok:

Yorum Gönder