添加依赖
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
实体类
package cn.clboy.springbootjpa.entity;
import javax.persistence.*;
@Entity //使用JPA注解配置映射关系,告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名类名小写;
public class User {
@Id //这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY) //自增主键
private Integer id;
@Column(name = "last_name",length = 50) //这是和数据表对应的一个列
private String lastName;
@Column //省略默认列名就是属性名
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
DAO
package cn.clboy.springbootjpa.repository;
import cn.clboy.springbootjpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 继承JpaRepository来完成对数据库的操作
* 泛型是(实体类,主键)
*/
public interface UserRepository extends JpaRepository<User, Integer> {
}
配置文件
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
添加用户
- http://localhost:8080/user?lastName=zhangsan&email=123456@qq.com
- http://localhost:8080/user?lastName=lisi&email=78215646@qq.com
- http://localhost:8080/user/1,抛出500错误,原因是getOne方法使用的懒加载,获取到的只是代理对象,转换为json时会报错
解决懒加载
- 关闭懒加载,在实体类上加上@Proxy(lazy = false)注解
@Entity @Table(name = "tbl_user") @Proxy(lazy = false) public class User
- 转Json的时候忽略hibernateLazyInitializer和handler属性
@Entity @Table(name = "tbl_user") @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"}) public class User