spring data jpa

来源:互联网 发布:淘宝旗舰店是官方 编辑:程序博客网 时间:2024/06/08 11:26

1、准备工作

<dependencies>    <dependency>        <groupId>org.springframework.data</groupId>        <artifactId>spring-data-jpa</artifactId>        <!--如果是spring boot就导spring-boot-starter-data-jpa-->        <version>1.11.3.RELEASE</version>    </dependency></dependencies>

2、简单Dao层

public interface NewResourceRepository extends PagingAndSortingRepository<NewResource, Long>, JpaSpecificationExecutor<NewResource> {    List<NewResource> findByIdIn(Collection<Long> ids);    List<NewResource> findByRetryStatusAndOriginalCreateTimeNotNull(@Param("status") String status, Pageable pageable);    @Query(nativeQuery = true, value = "SELECT id,credential,message_id,original_create_time,payload,resource_type,retry_status,soap_action,update_time,url,payloadc,id_np_val,id_type from cdr_resource where retry_status in :status and update_time<:updateTime LIMIT :limit OFFSET :offset")    List<NewResource> findByRetryStatusInAndUpdateTimeBefore(@Param("status") List<String> status, @Param("updateTime") Date updateTime,                                                             @Param("limit") int limit, @Param("offset") int offset);}

a、定义接口继承相关接口,NewResource是表的实体类,主键是Long
b、PagingAndSortingRepository(分页功能)等其他Repository子类

List<NewResource> findByRetryStatusAndOriginalCreateTimeNotNull(@Param("status") String status, Pageable pageable);

c、JpaSpecificationExecutor可以扩展查询条件

public final class ResourceSpecification implements Specification<NotStoredResource> {    private final NotStoredResource resource;    public ResourceSpecification(NotStoredResource resource) {        this.resource = resource;    }    @Override    public Predicate toPredicate(Root<NotStoredResource> root, CriteriaQuery<?> query, CriteriaBuilder cb) {        List<Predicate> predicateList = Lists.newArrayList();        if (StringUtils.isNotBlank(resource.getMessageId())) predicateList.add(cb.equal(root.get("messageId").as(String.class), resource.getMessageId()));//相等        if (StringUtils.isNotBlank(resource.getPayload())) predicateList.add(cb.like(root.get("payload").as(String.class), "%" + resource.getPayload() + "%"));//模糊匹配        query.orderBy(cb.desc(root.get("originalCreateTime").as(Date.class)));//按某个字段降序排列        Predicate[] predicates = new Predicate[predicateList.size()];        return cb.and(predicateList.toArray(predicates));    }}>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Specification specification = new ResourceSpecification(final NewResource re);Page<NewResource> = newResourceRepository.findAll(specification, pageable);

3.用方法代替SQL语句

countByRetryStatusInAndUpdateTimeBefore(List status, Date updateTime)——retryStatus在集合内并且updateTime在某个时间前的数据记录条数

findByIdentifierNpValIsNullAndRetryStatusNotInAndOriginalCreateTimeNotNull(List nonRetry, Pageable pageable)——identifierNpVal为空,并且retryStatus不在集合内,并且originalCreateTime不为空

findFirstByResourceIdOrderByVersionDesc——通过resourceId查找并按version降序排列然后取第一条

4.基本原理

所有自定义xxxRepository接口里面的方法,最终都是通过SimpleJpaRepository去调用的hibernate接口实现的.如果这个实现类里面某些方法需要重定义,我们可以新建一个类继承它如叫CustomJpaRepository,然后覆写该方法即可。最后将其注入

public class CustomRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {    @SuppressWarnings("rawtypes")    protected RepositoryFactorySupport createRepositoryFactory(EntityManager em) {        return new CustomRepositoryFactory(em);    }    private static class CustomRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory {        private final EntityManager em;        public CustomRepositoryFactory(EntityManager em) {            super(em);            this.em = em;        }        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {            return CustomJpaRepository.class;        }    }}>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>@EnableJpaRepositories(repositoryFactoryBeanClass = CustomRepositoryFactoryBean.class)//在启动类(spring boot)加上这句注释即可