JPA的使用
# Spring Data JPA的使用
JPA顾名思义就是Java Persistence API的意思,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。
- SpringBoot使用SpringDataJPA完成CRUD操作. 数据的存储以及访问都是最为核心的关键部分,现在有很多企业采用主流的数据库,如关系型数据库:MySQL,Oracle,SQLServer。非关系型数据库:redis,mongodb等.
- Spring Data JPA 是Spring Data 的一个子项目,它通过提供基于JPA的Repository极大了减少了操作JPA的代码。
# 1、导入相关依赖并配置文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url:
username:
password:
jpa:
database: mysql
# 日志中显示sql语句
show-sql: true
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
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
# 2、JPA使用
# 步骤一:新建实体类并添加JPA注解
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "article")
public class Article implements Serializable {
@Id
@GeneratedValue
@Column(name = "a_id")
private Integer aId;
@Column(name = "article_title")
private String articleTitle;
@Column(name = "article_content")
private String articleContent;
@Column(name = "head_image")
private String headImage;
@Column(name = "article_author")
private String articleAuthor;
@Column(name = "type_number")
private Integer typeNumber;
@Column(name = "pageviews")
private Integer pageViews;
@Column(name = "create_time")
private String createTime;
@Column(name = "is_state")
private Integer isState;
}
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
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
# 步骤二:新建接口ArticleDao
/**
* JpaRepository<T,ID> 提供简单的数据操作接口
* Article 实体类类型
* Integer 主键类型
*
* JpaSpecificationExecutor<T> 提供复杂查询接口
* Article 实体类类型
*
* Serializable 序列化
*/
@Repository
public interface ArticleDao extends JpaRepository<Article,Integer>,JpaSpecificationExecutor<Article>,Serializable{
//这里没有代码,注意没有代码..........
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 步骤三:测试
@SpringBootTest
class Springboot07JpaApplicationTests {
@Autowired
private ArticleDao articleDao;
@Test
void contextLoads() {
List<Article> articleList = articleDao.findAll();
articleList.forEach(System.out::println);
}
}
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
# 3、JPA查询方法命令规范
关键字 | 方法命名 | sql where字句 |
---|---|---|
And | findByNameAndPwd | where name= ? and pwd =? |
Or | findByNameOrSex | where name= ? or sex=? |
Is,Equals | findById,findByIdEquals | where id= ? |
Between | findByIdBetween | where id between ? and ? |
LessThan | findByIdLessThan | where id < ? |
LessThanEquals | findByIdLessThanEquals | where id <= ? |
GreaterThan | findByIdGreaterThan | where id > ? |
GreaterThanEquals | findByIdGreaterThanEquals | where id > = ? |
After | findByIdAfter | where id > ? |
Before | findByIdBefore | where id < ? |
IsNull | findByNameIsNull | where name is null |
isNotNull,NotNull | findByNameNotNull | where name is not null |
Like | findByNameLike | where name like ? |
NotLike | findByNameNotLike | where name not like ? |
StartingWith | findByNameStartingWith | where name like '?%' |
EndingWith | findByNameEndingWith | where name like '%?' |
Containing | findByNameContaining | where name like '%?%' |
OrderBy | findByIdOrderByXDesc | where id=? order by x desc |
Not | findByNameNot | where name <> ? |
In | findByIdIn(Collection<?> c) | where id in (?) |
NotIn | findByIdNotIn(Collection<?> c) | where id not in (?) |
True | findByAaaTue | where aaa = true |
False | findByAaaFalse | where aaa = false |
IgnoreCase | findByNameIgnoreCase | where UPPER(name)=UPPER(?) |
# 4、JPQL语法生成
public interface StandardRepository extends JpaRepository<Standard, Long> {
// JPA的命名规范
List<Standard> findByName(String name);
// 自定义查询,没有遵循命名规范
@Query("from Standard where name = ?")
Standard findByNamexxxx(String name);
// 遵循命名规范,执行多条件查询
Standard findByNameAndMaxLength(String name, Integer maxLength);
// 自定义多条件查询
@Query("from Standard where name = ?2 and maxLength = ?1")
Standard findByNameAndMaxLengthxxx(Integer maxLength, String name);
// 使用”标准”SQL查询,以前mysql是怎么写,这里继续
@Query(value = "select * from T_STANDARD where C_NAME = ? and C_MAX_LENGTH = ?",
nativeQuery = true)
Standard findByNameAndMaxLengthxx(String name, Integer maxLength);
// 模糊查询
Standard findByNameLike(String name);
@Modifying // 代表本操作是更新操作
@Transactional // 事务注解
@Query("delete from Standard where name = ?")
void deleteByName(String name);
@Modifying // 代表本操作是更新操作
@Transactional // 事务注解
@Query("update Standard set maxLength = ? where name = ?")
void updateByName(Integer maxLength, String name);
}
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
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
# 5、JPA URUD示例
modle:Article.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "article")
public class Article implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "a_id")
private int aId;
@Column(name = "article_title")
private String articleTitle;
@Column(name = "article_content")
private String articleContent;
@Column(name = "head_image")
private String headImage;
@Column(name = "article_author")
private String articleAuthor;
@Column(name = "type_number")
private int typeNumber;
private int pageviews;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "create_time")
private Date createTime;
@Column(name = "is_state")
private int isState;
}
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
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
dao:ArticleDao.java
public interface ArticleDao extends JpaRepository<Article, Integer>, JpaSpecificationExecutor<Article>, Serializable {
List<Article> findByArticleTitleContaining(String keywords);
//自定义方法
@Query("select art from Article art where art.articleTitle like %?1% or art.articleContent like %?1%")
Page<Article> findByLike(String keywords, Pageable pageable);
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
service:ArticleService.java
public interface ArticleService {
Page<Article> findByLike(String keywords, int page, int pageSize);
public void delArticle(int aId);
public void updateArticle(Article article);
public void addArticle(Article article);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
serviceImpl:ArticleServiceImpl.java
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleDao articleDao;
@Override
public Page<Article> findByLike(String keywords, int page, int pageSize) {
Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
PageRequest pageable = PageRequest.of(page - 1, pageSize, sort);
Page<Article> pageResult = articleDao.findByLike(keywords, pageable);
return pageResult;
}
@Override
public void delArticle(int aId) {
articleDao.deleteById(aId);
}
@Override
public void updateArticle(Article article) {
articleDao.save(article);
}
@Override
public void addArticle(Article article) {
articleDao.save(article);
}
}
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
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
controller:ArticleController.java
@RestController
@Api(value = "文章的接口", description = "文章的接口")
public class ArticleController {
@Autowired
private ArticleService articleService;
@GetMapping("Article")
public ResponseData<Article> selAllArticle(
@RequestParam(value = "keywords", required = true, defaultValue = "") String keywords,
@RequestParam(value = "page", required = true, defaultValue = "1") Integer page,
@RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
Page<Article> pageResult = articleService.findByLike(keywords, page, pageSize);
ResponseData<Article> rd = new ResponseData<Article>(200, "success", pageResult.getTotalElements(), pageResult.getContent());
return rd;
}
@DeleteMapping("Article/{aId}")
public void delArticleById(@PathVariable int aId) {
articleService.delArticle(aId);
}
@PutMapping("Article")
public void updateArticleById(@RequestBody Article article) {
articleService.updateArticle(article);
}
@PostMapping("Article")
public void addArticleById(@RequestBody Article article) {
articleService.addArticle(article);
}
}
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
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
# 6、JPA实现分页和模糊查询
modle:Article.java
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "article")
public class Article implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "a_id")
private int aId;
@Column(name = "article_title")
private String articleTitle;
@Column(name = "article_content")
private String articleContent;
@Column(name = "head_image")
private String headImage;
@Column(name = "article_author")
private String articleAuthor;
@Column(name = "type_number")
private int typeNumber;
private int pageviews;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "create_time")
private Date createTime;
@Column(name = "is_state")
private int isState;
}
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
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
dao:ArticleDao.java
public interface ArticleDao extends JpaRepository<Article, Integer>, JpaSpecificationExecutor<Article>, Serializable {
@Query("select art from Article art where art.articleTitle like %?1% or art.articleContent like %?1%")
Page<Article> findByLike(String keywords, Pageable pageable);
}
1
2
3
4
5
2
3
4
5
service:ArticleService.java
public interface ArticleService {
Page<Article> findByLike(String keywords, int page, int pageSize);
}
1
2
3
4
2
3
4
serviceImpl:ArticleServiceImpl.java
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleDao articleDao;
@Override
public Page<Article> findByLike(String keywords, int page, int pageSize) {
Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
PageRequest pageable = PageRequest.of(page - 1, pageSize, sort);
Page<Article> pageResult = articleDao.findByLike(keywords, pageable);
return pageResult;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
controller:ArticleController.java
@RestController
@Api(value = "文章的接口", description = "文章的接口")
public class ArticleController {
@Autowired
private ArticleService articleService;
@GetMapping("Article")
public ResponseData<Article> selAllArticle(
@RequestParam(value = "keywords", required = true, defaultValue = "") String keywords,
@RequestParam(value = "page", required = true, defaultValue = "1") Integer page,
@RequestParam(value = "pageSize", required = true, defaultValue = "10") Integer pageSize) {
Page<Article> pageResult = articleService.findByLike(keywords, page, pageSize);
ResponseData<Article> rd = new ResponseData<Article>(200, "success", pageResult.getTotalElements(), pageResult.getContent());
return rd;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
编辑 (opens new window)