SpringDataJPA
2022-2-12 大约 1 分钟
# SpringDataJPA
# 环境
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--用于复杂查询-->
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-sql</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
</dependency>
<build>
<plugins>
<plugin>
<groupId>com.mysema.maven</groupId>
<artifactId>apt-maven-plugin</artifactId>
<version>1.1.3</version>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<configuration>
<!-- q类实体生成地址-->
<outputDirectory>target/generated-sources/java</outputDirectory>
<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 实现JpaRepository对象用于简单查询
public interface SysUserRepository extends JpaRepository<SysUser, Long> {
}
1
2
3
2
3
# 常用注解
- @Data
- @MappedSuperclass
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- @Column
- @Transient
- @Query:支持jpql查询,nativeQuery=true时使用sql查询
// 自定义dto接口
public interface PeopleDTO {
String getName();
Long getCount();
}
// jpa代理对象可以直接json化返回前端
@Query(value = "SELECT p.name AS name, COUNT(dp.people_id) AS count " +
"FROM people p INNER JOIN dream_people dp " +
"ON p.id = dp.people_id " +
"WHERE p.user_id = :userId " +
"GROUP BY dp.people_id " +
"ORDER BY p.name", nativeQuery = true)
List<PeopleDTO> findByPeopleAndCountByUserId(@Param("userId") Long userId);
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 简单查询api
- findOne(id):根据id查询
- findAll(): 查询全部
- findAllById(List<> ids):查询所有id
- save(customer):保存或者更新
- delete(id):根据id删除
- count():统计总条数
# 方法名称规则查询
public interface SysUserRepository extends JpaRepository<SysUser, Long> {
Page<SysRole> findByName(String name, Pageable page);
}
1
2
3
2
3
方法名称规则
# 注入JPAQueryFactory对象用于复杂查询
@Bean
public JPAQueryFactory jpaQueryFactory(EntityManager entityManager) {
return new JPAQueryFactory(entityManager);
}
public List<SysRole> listRolesByUserId(Long userId) {
return jpaQueryFactory.selectFrom(qSysRole)
.leftJoin(qSysUserRole).on(qSysRole.id.eq(qSysUserRole.roleId))
.where(qSysUserRole.userId.eq(userId)).fetch();
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10