学习Spring-Data-Jpa(十四)---自定义Repository
有些时候,我们需要自定义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的更多相关文章
- 学习Spring Data JPA
简介 Spring Data 是spring的一个子项目,在官网上是这样解释的: Spring Data 是为数据访问提供一种熟悉且一致的基于Spring的编程模型,同时仍然保留底层数据存储的特殊 ...
- Spring Data Jpa的四种查询方式
一.调用接口的方式 1.基本介绍 通过调用接口里的方法查询,需要我们自定义的接口继承Spring Data Jpa规定的接口 public interface UserDao extends JpaR ...
- Spring Data - Spring Data JPA 提供的各种Repository接口
Spring Data Jpa 最近博主越来越懒了,深知这样不行.还是决定努力奋斗,如此一来,就有了一下一波复习 演示代码都基于Spring Boot + Spring Data JPA 传送门: 博 ...
- Spring Data JPA 提供的各种Repository接口作用
各种Repository接口继承关系: Repository : public interface UserRepository extends Repository<User, Integer ...
- 学习-spring data jpa
spring data jpa对照表 Keyword Sample JPQL snippet And findByLastnameAndFirstname - where x.lastname = ? ...
- Spring Data Jpa 查询返回自定义对象
转载请注明出处:http://www.wangyongkui.com/java-jpa-query. 今天使用Jpa遇到一个问题,发现查询多个字段时返回对象不能自动转换成自定义对象.代码如下: //U ...
- 在spring data jpa中使用自定义转换器之使用枚举转换
转载请注明http://www.cnblogs.com/majianming/p/8553217.html 在项目中,经常会出现这样的情况,一个实体的字段名是枚举类型的 我们在把它存放到数据库中是需要 ...
- Spring Data JPA 教程(翻译)
写那些数据挖掘之类的博文 写的比较累了,现在翻译一下关于spring data jpa的文章,觉得轻松多了. 翻译正文: 你有木有注意到,使用Java持久化的API的数据访问代码包含了很多不必要的模式 ...
- Spring Data JPA —— 快速入门
一.概述 JPA : Java Persistence API, Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中. Spring D ...
随机推荐
- 图像变化之Laplacian()函数 and Schaar()滤波及综合例子
先来 Laplacian()函数 #include<math.h> #include<opencv2/opencv.hpp> #include<string.h> ...
- delphi10.2断点调试dll
因为工作需要接触delphi10.2,需要调试dll,但是从网上查找的资料写的不是很清楚,我折腾了半天,我就动手写清楚操作步骤: 步骤1:用delphi10.2打开需要调试的dll,需要先打开,然后需 ...
- IDEA debug断点调试技巧
Debug用来追踪代码的运行流程,通常在程序运行过程中出现异常,启用Debug模式可以分析定位异常发生的位置,以及在运行过程中参数的变化.通常我们也可以启用Debug模式来跟踪代码的运行流程去学习三方 ...
- server.port 在单元测试中,调用的类或者方法这个地方获取到的端口号就会变成-1
@Value("${server.port}") 本文链接:https://blog.csdn.net/weixin_38342534/article/details/886985 ...
- 2019 搜狐java面试笔试题 (含面试题解析)
本人5年开发经验.18年年底开始跑路找工作,在互联网寒冬下成功拿到阿里巴巴.今日头条.搜狐等公司offer,岗位是Java后端开发,因为发展原因最终选择去了搜狐,入职一年时间了,也成为了面试官,之 ...
- JavaWeb 之 Filter 敏感词汇过滤案例
需求: 1. 对day17_case案例录入的数据进行敏感词汇过滤 2. 敏感词汇参考 src路径下的<敏感词汇.txt> 3. 如果是敏感词汇,替换为 *** 分析: 1. 对reque ...
- Linux负载模拟
转载:https://blog.csdn.net/F8qG7f9YD02Pe/article/details/79063392 CPU 下面命令会创建 CPU 负荷,方法是通过压缩随机数据并将结果发送 ...
- jsonpath 一个简单实用的工具
import jsonpath import json data = "{\"a\": \"11\", \"c\": {\&quo ...
- 二十六、聊聊mysql如何实现分布式锁
分布式锁的功能 分布式锁使用者位于不同的机器中,锁获取成功之后,才可以对共享资源进行操作 锁具有重入的功能:即一个使用者可以多次获取某个锁 获取锁有超时的功能:即在指定的时间内去尝试获取锁,超过了超时 ...
- Gitlab创建一个项目
1.安装git yum install git 2.生成密钥文件:使用ssh-keygen生成密钥文件.ssh/id_rsa.pub ssh-keygen 执行过程中输入密码,以及确认密码,并可设置密 ...