有些时候,我们需要自定义Repository实现一些特殊的业务场景。

1、自定义单个Repository

  1.1、首先提供一个片段接口和实现(接口的实现默认要使用Impl为后缀,实现本身不依赖spring-data,可以是常规的spring-bean,所以可以注入其他的bean,例如JdbcTemplate)。

/**
* @author caofanqi
*/
public interface StudentRepositoryCustomJdbc { List<Student> findStudentByJdbcName(String name); } /**
* 默认要以Impl结尾
* @author caofanqi
*/
public class StudentRepositoryCustomJdbcImpl implements StudentRepositoryCustomJdbc { @Resource
private JdbcTemplate jdbcTemplate; @Override
public List<Student> findStudentByJdbcName(String name) {
String sql = "SELECT * FROM cfq_jpa_student WHERE name = " + "'" + name + "'";
return jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(Student.class));
} }

  1.2、自己的Repository继承自定义接口,就可以使用拓展的功能了。

/**
* 继承jpa的repository,和自己自定义的扩展
* @author caofanqi
*/
public interface StudentRepository extends JpaRepositoryImplementation<Student,Long>, StudentRepositoryCustomJdbc {
}

  1.3、测试如下:

    @BeforeEach
void setup(){
Student s1 = Student.builder().name("张三").age(23).build();
Student s2 = Student.builder().name("李四").age(24).build();
Student s3 = Student.builder().name("王五").age(25).build(); studentRepository.saveAll(Lists.newArrayList(s1,s2,s3));
} @Test
void testFindStudentByJdbcName(){
List<Student> list = studentRepository.findStudentByJdbcName("张三");
list.forEach(s -> System.out.println(s.getName()));
}

  1.4、控制台打印:

Hibernate: insert into cfq_jpa_student (age, name) values (?, ?)
Hibernate: insert into cfq_jpa_student (age, name) values (?, ?)
Hibernate: insert into cfq_jpa_student (age, name) values (?, ?)
张三

  1.5、自定义扩展可以有多个。自定义的优先级高于spring-data为我们提供的。

/**
* 继承jpa的repository,和自己自定义的扩展
* @author caofanqi
*/
public interface StudentRepository extends JpaRepositoryImplementation<Student,Long>, StudentRepositoryCustomJdbc,StudentRepositoryCustom<Student,Long> {
}
/**
* 自定义student功能
*
* @author caofanqi
*/
public interface StudentRepositoryCustom<T,ID> { Optional<T> findById(ID id); } /**
* 自定义实现repository功能
*
* @author caofnqi
*/
@Slf4j
public class StudentRepositoryCustomImpl<T,ID> implements StudentRepositoryCustom<T,ID> { @PersistenceContext
private EntityManager entityManager; @Override
public Optional<T> findById(ID id) {
log.info("自定义的findById");
T t = (T) entityManager.find(Student.class, id);
return Optional.of(t);
}
}

  

1.6、可以通过@EnableJpaRepositories的repositoryImplementationPostfix属性自定义后缀,默认是Impl。

/**
* 启动类
* @author caofanqi
*/
@SpringBootApplication
@EnableAsync
@EnableJpaRepositories(repositoryImplementationPostfix = "MyPostfix")
public class StudySpringDataJpaApplication { public static void main(String[] args) {
SpringApplication.run(StudySpringDataJpaApplication.class, args);
} }

2、自定义BaseRepository

  2.1、SpringDataJpa为我们提供的代理类其实是SimpleJpaRepository。  

  

  2.2、如果我们想要对所有的Repository的保存操作都进行记录日志,我们可以自定义BaseRepository,来充当代理类。(还可以是逻辑删除等场景)

    2.2.1、自定义baseRepository

/**
* 自定义base Repository
*
* @author caofanqi
*/
@Slf4j
public class MyRepositoryImpl<T,ID> extends SimpleJpaRepository<T,ID> { private final EntityManager entityManager; MyRepositoryImpl(JpaEntityInformation entityInformation, EntityManager entityManager) {
super(entityInformation, entityManager);
this.entityManager = entityManager;
} @Override
public <S extends T> S save(S entity) {
S save = super.save(entity);
log.info("保存了:{}",save);
return save;
} }

  2.2.2、告知Spring-Data-Jpa使用我们自定义的baseRepository

/**
* 启动类
* @author caofanqi
*/
@SpringBootApplication
@EnableAsync
@EnableJpaRepositories(
/*queryLookupStrategy = QueryLookupStrategy.Key.CREATE_IF_NOT_FOUND*/
/* ,repositoryImplementationPostfix = "MyPostfix",*/
repositoryBaseClass = MyRepositoryImpl.class)
public class StudySpringDataJpaApplication { public static void main(String[] args) {
SpringApplication.run(StudySpringDataJpaApplication.class, args);
} }

  2.2.3、再次测试testSave方法,如下

  

3、entityManager执行原生复杂sql返回DTO

  使用方法派生查询和@Query注解查询时,我们可以使用投影来面向对象编程,但是使用entityManager执行原生sql复杂sql时,怎么返回实体呢?如下:

  3.1、DTO

/**
* entityManager使用的结果映射,需要一个无参构造函数与set方法,这一点与投影不一样
* @author caofanqi
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentAgeAndAgeCountDTO { private Integer age; private Long ageCount; }

  3.2、查询方法

    public List<StudentAgeAndAgeCountDTO> findCountGroupByAge(){

        /*
*sql可以是更复杂的
*/
String sql = "SELECT age,count(*) AS ageCount FROM cfq_jpa_student GROUP BY age "; Query nativeQuery = entityManager.createNativeQuery(sql);
nativeQuery.unwrap(NativeQuery.class)
//设置类型
.addScalar("age", StandardBasicTypes.INTEGER)
.addScalar("ageCount",StandardBasicTypes.LONG)
//设置返回bean
.setResultTransformer(Transformers.aliasToBean(StudentAgeAndAgeCountDTO.class));
return nativeQuery.getResultList(); }

  3.3、测试及结果 

 

源码地址:https://github.com/caofanqi/study-spring-data-jpa

学习Spring-Data-Jpa(十四)---自定义Repository的更多相关文章

  1. 学习Spring Data JPA

    简介 Spring Data 是spring的一个子项目,在官网上是这样解释的: Spring Data 是为数据访问提供一种熟悉且一致的基于Spring的编程模型,同时仍然保留底层数据存储的特​​殊 ...

  2. Spring Data Jpa的四种查询方式

    一.调用接口的方式 1.基本介绍 通过调用接口里的方法查询,需要我们自定义的接口继承Spring Data Jpa规定的接口 public interface UserDao extends JpaR ...

  3. Spring Data - Spring Data JPA 提供的各种Repository接口

    Spring Data Jpa 最近博主越来越懒了,深知这样不行.还是决定努力奋斗,如此一来,就有了一下一波复习 演示代码都基于Spring Boot + Spring Data JPA 传送门: 博 ...

  4. Spring Data JPA 提供的各种Repository接口作用

    各种Repository接口继承关系: Repository : public interface UserRepository extends Repository<User, Integer ...

  5. 学习-spring data jpa

    spring data jpa对照表 Keyword Sample JPQL snippet And findByLastnameAndFirstname - where x.lastname = ? ...

  6. Spring Data Jpa 查询返回自定义对象

    转载请注明出处:http://www.wangyongkui.com/java-jpa-query. 今天使用Jpa遇到一个问题,发现查询多个字段时返回对象不能自动转换成自定义对象.代码如下: //U ...

  7. 在spring data jpa中使用自定义转换器之使用枚举转换

    转载请注明http://www.cnblogs.com/majianming/p/8553217.html 在项目中,经常会出现这样的情况,一个实体的字段名是枚举类型的 我们在把它存放到数据库中是需要 ...

  8. Spring Data JPA 教程(翻译)

    写那些数据挖掘之类的博文 写的比较累了,现在翻译一下关于spring data jpa的文章,觉得轻松多了. 翻译正文: 你有木有注意到,使用Java持久化的API的数据访问代码包含了很多不必要的模式 ...

  9. Spring Data JPA —— 快速入门

    一.概述 JPA : Java Persistence API, Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中. Spring D ...

随机推荐

  1. Feign调用时读取超时(Read timed out executing GET)解决

    解决方式(很多人比较关注,所以放在最前面): 因为Feign调用默认的超时时间为一分钟,一分钟接口不能返回就会抛出异常,所以在服务端的yml文件中增加如下配置即可解决: # feign调用超时时间配置 ...

  2. webbench网站测压工具源码分析

    /* * (C) Radim Kolar 1997-2004 * This is free software, see GNU Public License version 2 for * detai ...

  3. 一文搞定Flask

    Flask 一 .Flask简介 Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收h ...

  4. es常用操作

    1.查看所有索引 _cat/indices?v 2.删除索引 DELETE my_index 3.查询缓存 curl /my_index/_search?request_cache=true' -d' ...

  5. redis 5.0 CLUSTERDOWN The cluster is down

    安装 redis 集群,设置值报错,错误信息:redis 5.0  CLUSTERDOWN The cluster is down. 这个是由于安装错误导致的,需要重新进行 修复一下. 命令如下: [ ...

  6. win7下scrapy1.3.2安装

    刚开始学爬虫,网上搜了搜,目前最合适的是选scrapy. 先要安装scrapy. 很多的博客上用的教程都说,scrapy目前对python3支持不是很好.可是不能不学3啊. 先用anaconda最新版 ...

  7. json_rpc_2 implementation

    https://stackoverflow.com/questions/52670255/flutter-json-rpc-2-implementation import 'dart:convert' ...

  8. 交换ESCHAUNGE英语ESCHAUNGE交易所

    exchange From Middle English eschaunge, borrowed from Anglo-Norman eschaunge exchange 1.An act of ex ...

  9. 如何给SAP云平台购买的账号分配Process Integration服务

    在云平台控制台里,给global Account分配Integration Suite下面的Process Integration的API和Runtime两种服务: Process Integrati ...

  10. Hybris服务器启动日志分析

    build文件检测,使用b2c_acc recipit启动服务器:/home/jerrywang/Hybris/installer/recipes/b2c_acc/build.gradle The T ...