一、SpringData Jpa 入门
- maven依赖相关配置
<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-jdbc</artifactId>
</dependency>
- yml 相关配置
server:
port: 8080
servlet:
context-path: /
spring:
datasource:
url: jdbc:mysql://localhost:3306/test_jpa?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
username: root
password: 123456
jpa:
database: MySQL
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
show-sql: true
hibernate:
ddl-auto: update
ddl-auto: update
- create:每次运行程序时,都会重新创建表,故而数据会丢失
- create-drop:每次运行程序时会先创建表结构,然后待程序结束时清空表
- upadte:每次运行程序,没有表时会创建表,如果对象发生改变会更新表结构,原有数据不会清空,只会更新(推荐使用)
- validate:运行程序会校验数据与数据库的字段类型是否相同,字段不同会报错
- none: 禁用DDL处理
- model 实体类
实体类中常用注解:
@Entity :声明这个类是一个实体类
@Table:指定映射到数据库的表格
@Id :映射到数据库表的主键属性,一个实体只能有一个属性被映射为主键
@GeneratedValue:主键的生成策略
@Column配置单列属性
@Entity
@Table(name ="tb_user")
@Data
public class User {
@Id
@GenericGenerator(name ="idGenerator",strategy = "uuid")
@GeneratedValue(generator = "idGenerator")
private String id;
@Column(name ="username",unique= true, nullable = false, length = 64)
private String username;
@Column(name = "password", nullable = false,length =64)
private String password;
@Column(name ="email",length = 64)
private String email;
}
主键采用UUID策略
@Gene