添加依赖
<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: rootpassword: 123456url: jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: com.mysql.cj.jdbc.DriverinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,wallmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: 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