普通JpaRepository类
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>{
}
JpaRepository一般的筛选查询,均可以通过findBy
的形式解决,总的很好用,但是总有一部分的业务查询是需要JpaRepository不能解决的。这个时候,就需要在此基础上面增加自定义的Repository类了。
自定义Repository类
接口类
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
,关于它的标准查询,使用我放在后面再提。
使用自定义类Repository类
@Repository
public interface EmployeeRepository extends JpaRepository<Employee,Long>, EmployeeRepositoryCustom {
}
依旧按照JpaRepository的使用方式,只要简单继承就可以了。
EntityManager的标准查询
如果不想在java代码里面涉及太多的sql字符串,应该按照EntityManager的标准查询方式,进行数据库查询,如下:
@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
1. Working with Spring Data Repositories
Add Custom Functionality to a Spring Data Repository
来源:oschina
链接:https://my.oschina.net/u/168875/blog/1925896