spring data jpa

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)加上这句注释即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值