18 Aralık 2019 Çarşamba

SpringData JpaRepository ile JPA @NamedQuery Anotasyonu

Giriş
Açıklaması şöyle.
We can create named queries by using an external properties file, Java annotations, or an XML file. Spring Data JPA supports both JPQL and native SQL named queries.
JPA @NamedQuery İsmi
Açıklaması şöyle.
The name must be unique within your application persistence context. To reference the named query in your Spring Data JPA repository, its name should start with the name of the entity class, followed by a dot (.), and the name of the repository method. 
JPA @NamedQuery ve Spring @Query Farkı
Açıklaması şöyle.
The @NamedQuery annotation is very much similar to the @Query annotation. The only difference is the former is used to define finder queries directly on the entity class, whereas the latter is used in the repository interface method.
Repository Sınıfı
Açıklaması şöyle.
...referencing a named query is very simple. All you need to do is just create a method in the repository interface with the same name as of named query, pass the correct method parameters, and specify the return type of the query method.
1. jpa-named-queries.properties Dosyası
Dosyanın yolu şöyle. META-INF dizinini elle yaratmak gerekir.
src/main/resources/META-INF/jpa-named-queries.properties
Örnek
Dosyada şöyle bir satır olsun.
OrderBackupRecordEO.findX=\
    SELECT record FROM OrderBackupRecordEO record WHERE ...
Şöyle yaparız
@Repository
public interface AdminRepository extends JpaRepository<OrderBackupRecordEO, BigDecimal> {

    List<String> findX();
}
2. Java Anotasyonu
Örnek
Elimizde şöyle bir sınıf olsun.
@Entity 
@NoArgsConstructor
@AllArgsConstructor
@Data
@NamedQuery(name="Person.withNameAndAddressNamedQuery",
  query = "select p from Person p where p.name=?1 and p.address=?2")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;
    private Integer age;
    private String address;
}
Şöyle yaparız.
Person withNameAndAddressNamedQuery(String name, String address);

Hiç yorum yok:

Yorum Gönder