Blog

  • 首页

  • 关于

  • 标签

  • 分类

  • 归档

  • 搜索

springboot_jpa

发表于 2019-09-01 分类于 SpringBoot 阅读次数:
本文字数: 7.1k

引入依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
spring:
datasource:
url: jdbc:mysql://123.123.123.123/springboot_jpa?charset=utf8mb4&useSSL=false
username: root
password: 123456
# Hikari
hikari.maximum-pool-size: 20
hikari.minimum-idle: 5
# JPA
jpa:
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
show-sql: true
hibernate:
ddl-auto: none

创建一个实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Entity //表示一个实体类
@Table(name = "tb_user") //对应数据库中的表名
@Data
@ToString
@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"})
public class User {

@Id //主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增型id
@Column(name = "u_id")//对应数据库中的字段名
private Long id;
@Column(name = "u_name")
private String name;
@Column(name = "u_age")
private int age;
@Column(name = "dep_id")
private int dep_id;
}

创建一个Dao接口(操作实体类类型,实体类中主键属性的类型)

1
2
public interface UserDao extends JpaRepository<User,Long> {
}

直接使用这个接口就有很多的常用方法了。(实际上是会生成一个jdk动态代理对象SimpleJpaRepositry)

基本的单表操作(CRUD)

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
@Autowired
private UserDao userDao;

@PostMapping("user")
public ResponseEntity insertUser(@RequestBody User user){
User save = userDao.save(user);
return new ResponseEntity(save,HttpStatus.OK);
}
@DeleteMapping("user/{id}")
public ResponseEntity deleteUser(@PathVariable("id") Long id){
userDao.deleteById(id);
return new ResponseEntity(HttpStatus.OK);
}
@PutMapping("user/{id}")
public ResponseEntity updateUser(@RequestBody User user,@PathVariable("id") Long id){
user.setId(id);
User user1 = userDao.save(user);
return new ResponseEntity(user1, HttpStatus.OK);
}
@GetMapping("user/{id}")
public ResponseEntity findUserById(@PathVariable("id") int id){
User user = userDao.getOne(1L);
System.out.println(user);
return new ResponseEntity(user, HttpStatus.OK);
}

其中的save方法,用来更新和新增数据,根据是由存在id来判断是新增还是修改,有id的就是修改,没有的就是新增。

自定义查询

Spring Data JPA 可以根据接口方法名来实现数据库操作,主要的语法是 findXXBy、readAXXBy、queryXXBy、countXXBy、getXXBy 后面跟属性名称,利用这个功能仅需要在定义的 Repository 中添加对应的方法名即可,使用时 Spring Boot 会自动帮我们实现.

1
2
3
4
5
6
7
List<User> findByAge(int age);

List<User> findByNameAndAge(String name, int age);

List<User> findByNameLike(String name);

List<User> findByNameLikeAndAge(String name, int age);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@GetMapping("user5")
public ResponseEntity findByAge(@RequestParam(required = false) int age) {
List<User> userList = userDao.findByAge(age);
return new ResponseEntity(userList, HttpStatus.OK);
}

@GetMapping("user6")
public ResponseEntity findByNameAndAge(String name, int age) {
List<User> userList = userDao.findByNameAndAge(name, age);
return new ResponseEntity(userList, HttpStatus.OK);
}

@GetMapping("user7")
public ResponseEntity findByNameLike(String name) {
List<User> userList = userDao.findByNameLike("%" + name + "%");
return new ResponseEntity(userList, HttpStatus.OK);
}

@GetMapping("user8")
public ResponseEntity findByNameLikeAndAge(String name, int age) {
List<User> userList = userDao.findByNameLikeAndAge("%" + name + "%", age);
return new ResponseEntity(userList, HttpStatus.OK);
}

分页查询(page是从0开始的)

1
Page<User> findByAge(int age,Pageable pageable);
1
2
3
4
5
6
7
@GetMapping("user3")
public ResponseEntity findUserByAge(int age,int page,int size){
PageRequest pageRequest = PageRequest.of(page,size);
Page<User> userPage = userDao.findByAge(age,pageRequest);
List<User> userList = userPage.getContent();
return new ResponseEntity(userList,HttpStatus.OK);
}

只要加一个PageRequest参数,就可以进行分页查询。

排序

只有排序,没有分页

1
List<User> findByAge(int age, Sort sort);
1
2
3
4
5
6
7
@GetMapping("user3")
public ResponseEntity findUserByAge(int age) {
Sort sort = new Sort(Sort.Direction.DESC, "name");
//PageRequest pageRequest = PageRequest.of(page,size,sort);
List<User> userList = userDao.findByAge(age, sort);
return new ResponseEntity(userList, HttpStatus.OK);
}

既有排序,又有分页,sort参数要加在PageRequest中

1
Page<User> findByAge(int age, Pageable pageable);
1
2
3
4
5
6
7
8
@GetMapping("user3")
public ResponseEntity findUserByAge(int age,int page,int size){
Sort sort = new Sort(Sort.Direction.DESC, "name");
PageRequest pageRequest = PageRequest.of(page,size,sort);
Page<User> userPage = userDao.findByAge(age,pageRequest);
List<User> userList = userPage.getContent();
return new ResponseEntity(userList,HttpStatus.OK);
}

多条件查询

1
public interface UserDao extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {}

首先在dao接口上实现一个JpaSpecificationExecutor接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//使用equal:直接得到path对象(要比较的属性),然后进行比较即可
//使用like:得到path对象后,使用path.as来指定比较的参数类型,再去比较
@GetMapping("user4")
public ResponseEntity MohuSearch(String name, int age, int dep_id) {
List<User> userList = userDao.findAll(new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
//获取要比较的属性
Path<Object> name1 = root.get("name");
Path<Object> age1 = root.get("age");
Path<Object> dep_id1 = root.get("dep_id");
//比较条件
Predicate like = criteriaBuilder.like(name1.as(String.class), "%" + name + "%");
Predicate equal1 = criteriaBuilder.equal(age1, age);
Predicate equal = criteriaBuilder.equal(dep_id1, dep_id);
//查询条件拼接
Predicate and = criteriaBuilder.and(like, equal1, equal);
return and;
}
});
return new ResponseEntity(userList, HttpStatus.OK);
}

使用findAll方法,自定义Specification对象,拼接查询条件。
还可以加上分页和排序,方法与之前相同。

自定义sql和jqpl(使用@Query)

sql:面向表的

1
select * from tb_user

jqpl:面向对象的

1
select user.id,user.name from User u

使用@Query注解,就可以自定义sql(加上nativaQuery=true)或者jqpl语句进行查询

1
2
3
4
5
6
//使用sql语句
@Query(nativeQuery = true, value = "select * from tb_user u where u.u_name = :name")
List<User> findUserByName(@Param("name") String name);
//使用jpql语句
@Query(value = "select new com.example.jpa_demo.vo.UserVo(u.id,u.name,u.age,u.dep_id,d.name) from User u, com.example.jpa_demo.pojo.Department d where u.dep_id = d.id")
List<UserVo> findUserAndDepartment();

使用@Query进行更新或删除

1
2
3
4
@Query(value = "update User u set u.name=:#{#user.name},u.age=:#{#user.age},u.dep_id=:#{#user.dep_id} where u.id = :id")
@Modifying
@Transactional
int updateUser(@Param("user") User user,@Param("id") Long id);
1
2
3
4
5
@GetMapping("user/{id}")
public ResponseEntity updateUser1(@RequestBody User user,@PathVariable("id") long id){
int i = userDao.updateUser(user,id);
return i==1 ? new ResponseEntity("success",HttpStatus.OK) : new ResponseEntity("fail",HttpStatus.OK);
}

如果要进行更新/删除操作时,需要加个@Transactional注解,同时需要加上@modifying注解,默认开启的事务是可读的,开启之后就会关闭可读。

demo


------ 已触及底线感谢您的阅读 ------
麻辣香锅不要辣 微信支付

微信支付

  • 本文作者: 麻辣香锅不要辣
  • 本文链接: https://http://ybhub.gitee.io/2019/09/01/springboot-jpa/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
# SpringBoot # SpringBoot-Data-JPA
springboot-security
jwt
  • 文章目录
  • 站点概览
麻辣香锅不要辣

麻辣香锅不要辣

21 日志
11 分类
20 标签
GitHub 简书
  1. 1. 引入依赖
  2. 2. 配置
  3. 3. 创建一个实体类
  4. 4. 创建一个Dao接口(操作实体类类型,实体类中主键属性的类型)
  5. 5. 基本的单表操作(CRUD)
  6. 6. 自定义查询
  7. 7. 分页查询(page是从0开始的)
  8. 8. 排序
    1. 8.1. 只有排序,没有分页
    2. 8.2. 既有排序,又有分页,sort参数要加在PageRequest中
  9. 9. 多条件查询
  10. 10. 自定义sql和jqpl(使用@Query)
  11. 11. 使用@Query进行更新或删除
© 2019 – 2020 麻辣香锅不要辣 | 站点总字数: 20.4k字
|
0%