1.pom依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2.application.properties配置文件
server.port=8080
server.servlet.context-path=/jpa
logging.level.com.yuchen.VOS.dao=debug
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#配置mysql8.0,阿里连接池需要引入区域信息才能启动
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://abc.com:3306/springboot_jpa_demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Chongqing
spring.datasource.username=root
spring.datasource.password=123456
#阿里druid连接池驱动配置信息
#初始化大小,最小,最大
spring.datasource.initialSize=2
spring.datasource.minIdle=2
spring.datasource.maxActive=15
#配置获取连接等待超时的时间
spring.datasource.maxWait=5000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
#配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
#打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
#配置阿里数据源的扩展过滤器
#WallFilter:Druid防御SQL注入攻击的防火墙,会在jdbc底层执行时对sql语句进行审查,防止sql注入,并支持mysql,orcale等数据库的语法
#statFilter:开启监控界面的sql统计
spring.datasource.filters=stat,wall,log4j
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# JPA配置,驼峰命名是自动的
spring.jpa.database = MYSQL
# 是否将执行的sql语句显示到控制台,正式环境建议关闭
spring.jpa.show-sql = true
# Hibernate ddl auto 参数用来配置是否开启自动更新数据库表结构,可取create、create-drop、update、validate、none五个值
#create 每次加载hibernate时,先删除已存在的数据库表结构再重新生成;
#create-drop 每次加载hibernate时,先删除已存在的数据库表结构再重新生成,当sessionFactory关闭时也会先删除已存在的数据库表结构再重新生成
#update 只在第一次加载hibernate时自动生成数据库表结构,以后再次加载hibernate时根据model类自动更新表结构;
#validate 每次加载hibernate时,验证数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
#none 什么都不做
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
#设置Hibernate使用的数据库方言
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
3.定义实体类
@Entity //用来标记该类是一个JPA实体类
@Table(name = "ums_user") //映射数据库表,name为数据库的表名
public class User implements Serializable {
private static final long serialVersionUID = -679176727475076780L;
@Id //定义记录的唯一标识
@GeneratedValue(strategy = GenerationType.AUTO) //定义记录的生成规则
private Long id;
private String username;
private String password;
private String nickName;
private Integer level;
@Transient //表示该字段不和数据库字段关联
private Integer status;
private Integer isDelete;
@Column(name = "create_time", columnDefinition = "DATETIME")
private Date createTime;
@Column(nullable = true, columnDefinition = "decimal(11,2)")
private BigDecimal tradeTotalMoney;
//get、set省略
}
4.dao层继承 Repository<实体类型,主键id的类型>
public interface UserDao extends JpaRepository<User,Long> {
//如果需要自己写sql,使用Query即可,
@Query("select e.id as employeeId,e.name as employeeName,d.id as departmentId,d.name as departmentName from Employee e , Department d where e.id= ?1 and d.id= ?2")
EmployeeDetail getEmployeeJoinDepartment(Long eid, Long did);
}
5.service层与实现类
public interface UserService {
User save(User user);
boolean delete(Long id);
boolean update(User user);
List<User> listAll();
Page<User> list(Integer pageNo,Integer pageSize);
User getUser(Long id);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User save(User user) {
User save = userDao.save(user);
return save;
}
@Override
public boolean delete(Long id) {
userDao.deleteById(id);
return false;
}
@Override
public boolean update(User user) {
User save = userDao.save(user);
return false;
}
@Override
public List<User> listAll() {
return userDao.findAll();
}
@Override
public Page<User> list(Integer pageNo, Integer pageSize) {
Pageable pageable = PageRequest.of(pageNo,pageSize);
return userDao.findAll(pageable);
}
@Override
public User getUser(Long id) {
try {
return userDao.findById(id).get();
}catch (NoSuchElementException e){
return null;
}
}
}
6.controller层
@Api(tags = "用户管理")
@RequestMapping("/user")
@RestController
public class UserController {
Logger log = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@ApiOperation(value = "添加功能")
@PostMapping(path = "/add")
public Result add(@RequestBody User user){
if(StringUtils.isEmpty(user.getUsername())){
return Result.error500("参数错误",null);
}
log.info(user.toString());
userService.save(user);
return Result.ok("添加成功",null);
}
@ApiOperation(value = "删除功能")
@DeleteMapping(path = "/delete")
public Result delete(@RequestParam("id") String id){
if(StringUtils.isEmpty(id)){
return Result.error500("参数错误",null);
}
userService.delete(Long.valueOf(id));
return Result.ok("删除成功",null);
}
@ApiOperation(value = "修改功能")
@PutMapping(path = "/update")
public Result update(User user){
userService.update(user);
return Result.ok("修改成功",null);
}
@ApiOperation(value = "分页查询")
@GetMapping(path = "/list")
public Result list(@RequestParam(value = "pageNo",defaultValue = "0") Integer pageNo,
@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
Page<User> list = userService.list(pageNo, pageSize);
return Result.ok(null,list);
}
@ApiOperation(value = "详情")
@GetMapping(path = "/details/{id}")
public Result details(@PathVariable("id")Long id){
User user = userService.getUser(id);
if(user==null){
return Result.error500("用户不存在",null);
}
return Result.ok("",user);
}
}
7.分页查询测试打印如下
JPA Page类属性如下
{
"status": 200,
"message": null,
"data": {
"content": [
{
"id": 3,
"username": "aaaa",
"createTime": null
},
{
"id": 4,
"username": "xxx",
"createTime": null
}
],
"pageable": {
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"offset": 0,
"pageSize": 10,
"pageNumber": 0,
"unpaged": false,
"paged": true
},
"totalPages": 1,
"totalElements": 2,
"last": true,
"size": 10,
"number": 0,
"sort": {
"sorted": false,
"unsorted": true,
"empty": true
},
"numberOfElements": 2,
"first": true,
"empty": false
},
"time": "2020-09-15 16:48:24"
}