JPA-Java Persistence API
The Spring Data Generated DAO – No More DAO Implementations
Spring Data takes this simplification one step further and makes it possible to remove the DAO implementations entirely. The interface of the DAO is now the only artifact that we need to explicitly define.
In order to start leveraging the Spring Data programming model with JPA, a DAO interface needs to extend the JPA specific Repository interface, JpaRepository. This will enable Spring Data to find this interface and automatically create an implementation for it.
Features
- Simply define a new method in the interface
- Provide the actual JPQL query by using the @Query annotation
- Use the more advanced Specification and Querydsl support in Spring Data
- define custom queries via JPA Named Queries
Composite Primary Keys
- The composite primary key class must be public.
- It must have a no-arg constructor.
- It must define the equals() and hashCode() methods.
- It must be Serializable.
- IdClass Annotation
public class StockKey implements Serializable {
private String stockId;
private String lotId;
// default constructor
public AccountId(String stockId, String lotId) {
this.stockId= stockId;
this.lotId= lotId;
}
// equals() and hashCode()
}
@Entity
@IdClass(StockKey.class)
public class Stock{
@Id
private String stockId;
@Id
private String lotId;
// other fields, getters and setters
} - EmbeddedId Annotation
@Embeddable
public class StockKey implements Serializable {
private String stockId;
private String lotId;
// default constructor
public AccountId(String stockId, String lotId) {
this.stockId= stockId;
this.lotId= lotId;
}
}
@Entity
public class Book {
@EmbeddedId
private StockKey stockId;
// constructors, other fields, getters and setters
}
@Query(value = "SELECT e FROM Employee e")
List<Employee> findAllEmployees(Sort sort);
@Query("SELECT e FROM Employee e WHERE e.name = :name and e.salary = :salary")
Employee findEmployeeByNameAndSalaryNamedParameters( @Param("name") String name,
@Param("salary") Long salary);
public interface IFooDAO extends JpaRepository<Foo, Long> {
Foo findByName(String name);
}
@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);
@Query(value = "SELECT * FROM Employee e WHERE e.salary = ?1", nativeQuery = true)
Employee findEmployeeBySalaryNative(Long salary);
PagingAndSortingRepository
}
Pageable sortedByName = PageRequest.of(0, 3, Sort.by("name"));
Pageable sortedByPriceDesc = PageRequest.of(0, 3, Sort.by("price").descending());
Pageable sortedByPriceDescNameAsc =
PageRequest.of(0, 5, Sort.by("price").descending().and(Sort.by("name")));
Comments
Post a Comment