import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface EmployeeRepository extends JpaRepository<Employee,Long>{ }
JpaRepository通常的篩選查詢,都可以經過findBy
的形式解決,總的很好用,可是總有一部分的業務查詢是須要JpaRepository不能解決的。這個時候,就須要在此基礎上面增長自定義的Repository類了。html
import java.util.List; public interface EmployeeRepositoryCustom { List<Employee> getFirstNamesLike(String firstName); }
import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.List; @Repository public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom { @PersistenceContext private EntityManager entityManager; @Override public List<Employee> getFirstNamesLike(String firstName) { Query query = entityManager.createNativeQuery("SELECT em.* FROM spring_data_jpa_example.employee as em " + "WHERE em.firstname LIKE ?", Employee.class); query.setParameter(1, firstName + "%"); return query.getResultList(); } }
**Note:**實現類的命名必須是這裏實現類的命名bean名+RepositoryImpl
;這裏注入了EntityManager
,關於它的標準查詢,使用我放在後面再提。java
@Repository public interface EmployeeRepository extends JpaRepository<Employee,Long>, EmployeeRepositoryCustom { }
依舊按照JpaRepository的使用方式,只要簡單繼承就能夠了。spring
若是不想在java代碼裏面涉及太多的sql字符串,應該按照EntityManager的標準查詢方式,進行數據庫查詢,以下:sql
@Repository public class EmployeeRepositoryImpl implements EmployeeRepositoryCustom { @PersistenceContext private EntityManager entityManager; @Override public List<Employee> getFirstNamesLike(String firstName) { // Query query = entityManager.createNativeQuery("SELECT em.* FROM spring_data_jpa_example.employee as em " + // "WHERE em.firstname LIKE ?", Employee.class); // query.setParameter(1, firstName + "%"); // return query.getResultList(); CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Employee> query = builder.createQuery(Employee.class); Root<Employee> root = query.from(Employee.class); Predicate predicate = builder.conjunction(); predicate = builder.and(predicate, builder.like(root.get("firstname"), "張三")); query.where(predicate); return entityManager.createQuery(query).getResultList(); } }
REST Query Language with Spring and JPA Criteria數據庫