一、项目起步
1.1 pom配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
1.2 yml配置
server:
port: 8037
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db_jpa?useSSL=false&useUnicode=true&characterEncoding=utf-8
username: root
password: root
jpa:
# 在建表的时候,将默认的存储引擎切换为InnoDB
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
# 控制台显示sql
show-sql: true
# 默认为false,意味着在视图渲染完成后,session会自动关闭
open-in-view: false
hibernate:
# 自动生成数据库表
ddl-auto: update
# 字段命名策略(默认)【驼峰转换下划线】
naming:
physical-strategy: org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy
1.3 实体类
1.3.1 用户
package com.qiangesoft.jpa.entity;
import java.io.Serializable;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/**
* 用户实体
*
* @author qiangesoft
* @date 2024-10-12
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "sys_user")
public class SysUser implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long createBy;
private Date createTime;
private Long updateBy;
private Date updateTime;
@Column(nullable = false, length = 50)
private String userName;
@Column(length = 255)
private String password;
@ManyToOne
@JoinColumn(name = "dept_id", nullable = false)
private SysDept dept;
@Column(nullable = false, length = 50)
private String nickName;
private Integer sex;
@Column(length = 50)
private String phoneNumber;
@Column(length = 50)
private String email;
@Column(length = 255)
private String avatar;
@Column(length = 500)
private String remark;
private Integer status;
@Column(name = "is_deleted", nullable = false)
private Boolean deleted;
/**
* 旧密码
* <p>非表字段</p>
*/
@Transient
private String oldPassword;
}
1.3.2部门
package com.qiangesoft.jpa.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* 部门实体
*
* @author qiangesoft
* @date 2024-10-12
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "sys_dept")
public class SysDept implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Long createBy;
private Date createTime;
private Long updateBy;
private Date updateTime;
@Column(nullable = false, length = 50)
private String deptName;
@ManyToOne
@JoinColumn(name = "parent_id")
private SysDept parent;
@Column(length = 500)
private String remark;
private Integer status;
@Column(name = "is_deleted", nullable = false)
private Boolean deleted;
}
1.4持久层
1.4.1 用户
package com.qiangesoft.jpa.dao;
import com.qiangesoft.jpa.entity.SysUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* 用户持久层
*
* @author qiangesoft
* @date 2024-10-12
*/
@Repository
public interface SysUserDao extends JpaRepository<SysUser, Long> {
}
1.4.2 部门
package com.qiangesoft.jpa.dao;
import com.qiangesoft.jpa.entity.SysDept;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* 部门持久层
*
* @author qiangesoft
* @date 2024-10-12
*/
@Repository
public interface SysDeptDao extends JpaRepository<SysDept, Long> {
}
1.5 启动
二、CRUD
2.1 业务层
package com.qiangesoft.jpa.service;
import com.qiangesoft.jpa.entity.SysUser;
import java.util.List;
/**
* 用户服务层
*
* @author qiangesoft
* @date 2024-10-11
*/
public interface SysUserService {
void save(SysUser sysUser);
void deleteById(Long id);
List<SysUser> finaAll();
SysUser findById(Long id);
}
package com.qiangesoft.jpa.service.impl;
import com.qiangesoft.jpa.dao.SysUserDao;
import com.qiangesoft.jpa.entity.SysUser;
import com.qiangesoft.jpa.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 用户服务层实现
*
* @author qiangesoft
* @date 2024-10-11
*/
@Service
public class SysUserServiceImpl implements SysUserService {
@Autowired
private SysUserDao sysUserDao;
@Override
public void save(SysUser sysUser) {
sysUserDao.save(sysUser);
}
@Override
public void deleteById(Long id) {
boolean exists = sysUserDao.existsById(id);
if (exists) {
sysUserDao.deleteById(id);
}
}
@Override
public List<SysUser> finaAll() {
return sysUserDao.findAll();
}
@Override
public SysUser findById(Long id) {
return sysUserDao.findById(id).orElse(null);
}
}
2.2 控制层
package com.qiangesoft.jpa.controller;
import com.qiangesoft.jpa.entity.SysUser;
import com.qiangesoft.jpa.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping("/sys-user")
@RestController
public class SysUserController {
@Autowired
private SysUserService sysUserService;
/**
* 新增或者修改
* @param sysUser
*/
@PostMapping
public void save(@RequestBody SysUser sysUser) {
sysUserService.save(sysUser);
}
/**
* 删除
* @param id
*/
@DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") Long id) {
sysUserService.deleteById(id);
}
/**
* 单个查询
* @param id
* @return
*/
@GetMapping("/{id}")
public SysUser findById(@PathVariable("id") Long id) {
return sysUserService.findById(id);
}
/**
* 查询列表
* @return
*/
@GetMapping
public List<SysUser> findAll() {
return sysUserService.finaAll();
}
}
2.3 测试
新增
单个查询
查询列表
删除
三、进阶
3.1 持久层
package com.qiangesoft.jpa.dao;
import com.qiangesoft.jpa.entity.SysUser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* 用户持久层
*
* @author qiangesoft
* @date 2024-10-12
*/
@Repository
public interface SysUserDao extends JpaRepository<SysUser, Long>, JpaSpecificationExecutor<SysUser> {
/**
* nativeQuery为true表示使用原生sql
* @param userName
* @return
*/
@Query(value = "select * from sys_user where user_name =:userName", nativeQuery = true)
SysUser findByUserName(@Param("userName") String userName);
@Query(value = "select u from SysUser u where u.nickName =:nickName")
Page<SysUser> pageByNickName(@Param("nickName") String nickName, Pageable pageable);
@Modifying
@Transactional
@Query("update SysUser u set u.nickName =:nickName where u.id =:id")
Integer updateById(@Param("nickName") String nickName, @Param("id") Long id);
}
3.2 业务层
package com.qiangesoft.jpa.service;
import com.qiangesoft.jpa.entity.SysUser;
import org.springframework.data.domain.Page;
import java.util.List;
/**
* 用户服务层
*
* @author qiangesoft
* @date 2024-10-11
*/
public interface SysUserService {
void save(SysUser sysUser);
void deleteById(Long id);
List<SysUser> finaAll();
Page<SysUser> page(Integer pageNum, Integer pageSize, String nickName);
SysUser findById(Long id);
}
package com.qiangesoft.jpa.service.impl;
import com.qiangesoft.jpa.dao.SysUserDao;
import com.qiangesoft.jpa.entity.SysUser;
import com.qiangesoft.jpa.service.SysUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
/**
* 用户服务层实现
*
* @author qiangesoft
* @date 2024-10-11
*/
@Service
public class SysUserServiceImpl implements SysUserService {
@Autowired
private SysUserDao sysUserDao;
@Override
public void save(SysUser sysUser) {
sysUserDao.save(sysUser);
}
@Override
public void deleteById(Long id) {
boolean exists = sysUserDao.existsById(id);
if (exists) {
sysUserDao.deleteById(id);
}
}
@Override
public List<SysUser> finaAll() {
return sysUserDao.findAll();
}
@Override
public Page<SysUser> page(Integer pageNum, Integer pageSize, String nickName) {
// 排序
List<Sort.Order> orders = new ArrayList<>();
orders.add(new Sort.Order(Sort.Direction.DESC, "id"));
Sort sort = Sort.by(orders);
// 分页
PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, sort);
if (nickName != null && !"".equals(nickName)) {
// 查询条件
Specification<SysUser> specification = (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicateList = new ArrayList<>();
predicateList.add(criteriaBuilder.equal(root.get("nickName"), nickName));
Predicate[] pre = predicateList.toArray(new Predicate[0]);
return criteriaQuery.where(pre).getRestriction();
};
return sysUserDao.findAll(specification, pageRequest);
// return sysUserDao.pageByNickName(nickName, pageRequest);
} else {
return sysUserDao.findAll(pageRequest);
}
}
@Override
public SysUser findById(Long id) {
sysUserDao.updateById("王五", 2L);
// SysUser admin = sysUserDao.findByUserName("admin");
return sysUserDao.findById(id).orElse(null);
}
}
3.3 控制层
package com.qiangesoft.jpa.controller;
import com.qiangesoft.jpa.entity.SysUser;
import com.qiangesoft.jpa.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RequestMapping("/sys-user")
@RestController
public class SysUserController {
@Autowired
private SysUserService sysUserService;
/**
* 新增或者修改
* @param sysUser
*/
@PostMapping
public void save(@RequestBody SysUser sysUser) {
sysUserService.save(sysUser);
}
/**
* 删除
* @param id
*/
@DeleteMapping("/{id}")
public void deleteById(@PathVariable("id") Long id) {
sysUserService.deleteById(id);
}
/**
* 单个查询
* @param id
* @return
*/
@GetMapping("/{id}")
public SysUser findById(@PathVariable("id") Long id) {
return sysUserService.findById(id);
}
/**
* 查询列表
* @return
*/
@GetMapping
public List<SysUser> findAll() {
return sysUserService.finaAll();
}
/**
* 分页查询
* @return
*/
@GetMapping("/page")
public Page<SysUser> page(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam String nickName) {
return sysUserService.page(pageNum, pageSize, nickName);
}
}
3.4 测试
四、代码仓库
https://gitee.com/qiangesoft/boot-business/tree/master/boot-business-jpa