Spring-data-jpa 笔记(一)
Spring Data JPA简介:
可以理解为 JPA 规范的再次封装抽象,底层还是使用了 Hibernate 的 JPA 技术实现,引用 JPQL(Java Persistence Query Language)查询语言,属于 Spring 的整个生态体系的一部分。
优势:
属于 Spring 的整个生态体系的一部分上手简单、开发效率高,ORM提供的能力他都提供,ORM框架没有提供的业务逻辑功能Spring-data-jpa也提供,全方位的解决用户的需求。使用Spring-data-jpa进行开发的过程中,常用的功能,我们几乎不需要写一条sql语句。
Spring Data操作主要特性:
提供模板操作,如 Spring Data Redis 和 Spring Data Riak;
强大的 Repository 和定制的数据储存对象的抽象映射;
对数据访问对象的支持(Auting 等)。
Spring Data JPA 的主要类及结构图:
七个大 Repository 接口:
Repository(org.springframework.data.repository);
CrudRepository(org.springframework.data.repository);
PagingAndSortingRepository(org.springframework.data.repository);
JpaRepository(org.springframework.data.jpa.repository);
QueryByExampleExecutor(org.springframework.data.repository.query);
JpaSpecificationExecutor(org.springframework.data.jpa.repository);
QueryDslPredicateExecutor(org.springframework.data.querydsl)。
两大 Repository 实现类:
SimpleJpaRepository(org.springframework.data.jpa.repository.support);
QueryDslJpaRepository(org.springframework.data.jpa.repository.support)。
Quick start:
以spring-boot2.1.3 ,mysql5.5+ 为技术场景
开发环境:
SPRING STS,MAVEN3.0+,JDK1.8
1、创建sringboot工程
完整工程结构图如下:
pom.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <project xmlns="http://maven.apache.org/POM/4.0.0"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5 <modelVersion>4.0.0</modelVersion>
6 <parent>
7 <groupId>org.springframework.boot</groupId>
8 <artifactId>spring-boot-starter-parent</artifactId>
9 <version>2.1.3.RELEASE</version>
10 <relativePath /> <!-- lookup parent from repository -->
11 </parent>
12 <groupId>com.zhengjiang</groupId>
13 <artifactId>springboot-demo</artifactId>
14 <version>0.0.1-SNAPSHOT</version>
15 <name>springboot-demo</name>
16 <description>Demo project for Spring Boot</description>
17
18 <properties>
19 <java.version>1.8</java.version>
20 </properties>
21
22 <dependencies>
23 <dependency>
24 <groupId>org.springframework.boot</groupId>
25 <artifactId>spring-boot-starter-web</artifactId>
26 </dependency>
27
28 <dependency>
29 <groupId>org.springframework.boot</groupId>
30 <artifactId>spring-boot-starter-test</artifactId>
31 <scope>test</scope>
32 </dependency>
33
34 <dependency>
35 <groupId>org.springframework.boot</groupId>
36 <artifactId>spring-boot-devtools</artifactId>
37 <optional>true</optional>
38 </dependency>
39
40 <dependency>
41 <groupId>org.springframework.boot</groupId>
42 <artifactId>spring-boot-starter-data-jpa</artifactId>
43 </dependency>
44
45 <dependency>
46 <groupId>mysql</groupId>
47 <artifactId>mysql-connector-java</artifactId>
48 <version>6.0.6</version>
49 </dependency>
50
51 <dependency>
52 <groupId>com.alibaba</groupId>
53 <artifactId>druid-spring-boot-starter</artifactId>
54 <version>1.1.6</version>
55 </dependency>
56 <!-- import lombok -->
57 <dependency>
58 <groupId>org.projectlombok</groupId>
59 <artifactId>lombok</artifactId>
60 <scope>provided</scope>
61 </dependency>
62 </dependencies>
63
64 <build>
65 <plugins>
66 <plugin>
67 <groupId>org.springframework.boot</groupId>
68 <artifactId>spring-boot-maven-plugin</artifactId>
69 <configuration>
70 <fork>true</fork>
71 </configuration>
72 </plugin>
73 </plugins>
74 </build>
75
76 </project>
2、修改application.properties 为yml配置
1 spring:
2 profiles:
3 active: product
4 datasource:
5 driver-class-name: com.mysql.jdbc.Driver
6 url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
7 username: root
8 password:
9 jpa:
10 hibernate:
11 ddl-auto: update
12 show-sql: true
13 jackson:
14 date-format: yyyy-MM-dd HH:mm:ss
15 time-zone: UTC
创建实体类UserInfo:
1 package com.zhengjiang.springboot.demo.entity; 2 3 import java.util.Date; 4 5 import javax.persistence.Entity; 6 import javax.persistence.GeneratedValue; 7 import javax.persistence.Id; 8 import javax.persistence.Table; 9 10 import org.springframework.stereotype.Component; 11 12 import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 13 14 import lombok.Data; 15 import lombok.ToString; 16 17 @Data 18 @ToString 19 @Entity 20 @Table(name = "t_sys_user") 21 @Component 22 @JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" }) 23 public class UserInfo{ 24 25 public UserInfo() {} 26 27 public UserInfo(String name) {this.name = name;} 28 @Id 29 @GeneratedValue 30 private Long id; //ID 31 private String name; //姓名 32 private String jobNumber; //工号 33 private Date createTime; //创建时间 34 }
创建一个 Repository
1 package com.zhengjiang.springboot.demo.respository;
2
3 import org.springframework.data.jpa.repository.JpaRepository;
4 import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
5
6 import com.zhengjiang.springboot.demo.entity.UserInfo;
7
8 public interface UserRepository extends JpaRepository<UserInfo, Long>,JpaSpecificationExecutor<UserInfo> {
9 UserInfo findByName(String name);
10 }
创建service 以及实现类
1 package com.zhengjiang.springboot.demo.service;
2
3 import java.util.List;
4
5 import org.springframework.data.domain.Page;
6
7 import com.zhengjiang.springboot.demo.entity.UserInfo;
8
9 public interface UserService {
10
11 UserInfo findById(Long id);
12 List<UserInfo> getUserList();
13 UserInfo getUserByName(String name);
14 UserInfo addUserInfo(UserInfo userInfo);
15 UserInfo updateUserInfoById(UserInfo userInfo);
16 void deleteUserInfoById(Long Id);
17 List<UserInfo>getCurrentUserList();
18 Page<UserInfo> getPageUserList();
19 }
1 package com.zhengjiang.springboot.demo.service.impl;
2
3 import java.util.List;
4
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.data.domain.Page;
7 import org.springframework.data.domain.Sort;
8 import org.springframework.stereotype.Service;
9 import org.springframework.data.domain.PageRequest;
10
11 import com.zhengjiang.springboot.demo.entity.UserInfo;
12 import com.zhengjiang.springboot.demo.respository.UserRepository;
13 import com.zhengjiang.springboot.demo.service.UserService;
14
15 @Service
16 public class UserServiceImpl implements UserService {
17 @Autowired
18 private UserRepository userRepository;
19
20 @Override
21 public UserInfo findById(Long id) {
22 return userRepository.getOne(id);
23 }
24 @Override
25 public List<UserInfo> getUserList() {
26 return userRepository.findAll();
27 }
28
29 @Override
30 public UserInfo getUserByName(String name) {
31 UserInfo userInfo = userRepository.findByName(name);
32 return userInfo;
33 }
34
35 @Override
36 public UserInfo addUserInfo(UserInfo userInfo) {
37 return userRepository.save(userInfo);
38 }
39
40 @Override
41 public UserInfo updateUserInfoById(UserInfo userInfo) {
42 return userRepository.save(userInfo);
43 }
44
45 @Override
46 public void deleteUserInfoById(Long id) {
47 userRepository.deleteById(id);
48 }
49
50 @Override
51 public List<UserInfo> getCurrentUserList() {
52 Sort sort=new Sort(Sort.Direction.DESC,"createTime");
53 return userRepository.findAll(sort);
54 }
55 @Override
56 public Page<UserInfo> getPageUserList() {
57 Sort sort=new Sort(Sort.Direction.DESC,"createTime");
58 PageRequest pageable=new PageRequest(0,5,sort);
59 userRepository.findAll(pageable);
60 return userRepository.findAll(pageable);
61 }
62 }
创建controller
1 package com.zhengjiang.springboot.demo.controller;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5 import java.util.List;
6 import java.util.TimeZone;
7
8 import javax.servlet.http.HttpServletRequest;
9
10 import org.springframework.beans.factory.annotation.Autowired;
11 import org.springframework.beans.propertyeditors.CustomDateEditor;
12 import org.springframework.data.domain.Page;
13 import org.springframework.web.bind.ServletRequestDataBinder;
14 import org.springframework.web.bind.annotation.GetMapping;
15 import org.springframework.web.bind.annotation.InitBinder;
16 import org.springframework.web.bind.annotation.PostMapping;
17 import org.springframework.web.bind.annotation.PutMapping;
18 import org.springframework.web.bind.annotation.RequestMapping;
19 import org.springframework.web.bind.annotation.RequestParam;
20 import org.springframework.web.bind.annotation.RestController;
21 import com.zhengjiang.springboot.demo.entity.UserInfo;
22 import com.zhengjiang.springboot.demo.service.UserService;
23
24 @RestController
25 @RequestMapping("/test")
26 public class TestController {
27
28 @Autowired
29 private UserService userService;
30
31 /**
32 *
33 * @param id
34 * @return
35 */
36 @GetMapping(value = "/getOne")
37 public UserInfo getOne(@RequestParam("id") Long id) {
38 return userService.findById(id);
39 }
40
41 /**
42 * 获取所有用户
43 * @return
44 */
45 @GetMapping(value = "/getUserList")
46 public List<UserInfo> getUserList() {
47 return userService.getUserList();
48 }
49
50 /**
51 * 根据用户名查找
52 * @param name
53 * @return
54 */
55 @GetMapping(value = "/getUserInfo")
56 public UserInfo getUserInfoByName(@RequestParam("name") String name) {
57 UserInfo u = userService.getUserByName(name);
58 return u;
59 }
60
61 /**
62 * 根据createTime倒序查询
63 * @return
64 */
65 @GetMapping(value = "/getCurrentUserList")
66 public List<UserInfo> getCurrentUserList(){
67 return userService.getCurrentUserList();
68 }
69
70 /**
71 * 分页查找
72 * @return
73 */
74 @GetMapping(value="/getPageUserList")
75 public Page<UserInfo> getPageUserList(){
76 return userService.getPageUserList();
77 }
78
79 /**
80 * 添加用户
81 * @param userInfo
82 * @return
83 */
84 @PostMapping(value = "/addUserInfo")
85 public UserInfo addUserInfo(UserInfo userInfo) {
86 return userService.addUserInfo(userInfo);
87 }
88
89 /**
90 * 更新用户
91 * @param userInfo
92 * @return
93 */
94 @PostMapping(value ="/updateUserInfo")
95 public UserInfo updateUserInfo(UserInfo userInfo){
96 return userService.updateUserInfoById(userInfo);
97 }
98
99 /**
100 * 删除用户
101 * @param id
102 */
103 @PostMapping(value="/deleteUserInfo")
104 public void deleteUserInfo(@RequestParam("id") Long id){
105 userService.deleteUserInfoById(id);
106 }
107
108 @InitBinder
109 protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
110 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
111 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));/*TimeZone时区,解决差8小时的问题*/
112 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
113 }
114 }
用postman 测试接口。