JPA上手
1.maven增加依赖2.数据实体类3.配置 JPA4.Dao5.测试
1.maven增加依赖
<dependency>
<groupId>org.springframework.boot
</groupId>
<artifactId>spring-boot-starter-data-jpa
</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok
</groupId>
<artifactId>lombok
</artifactId>
</dependency>
2.数据实体类
@Entity
@Table(name
= "t_users")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy
= GenerationType
.IDENTITY
)
@Column(name
= "id",length
= 32,nullable
= true)
private Integer id
;
@Column(name
= "name")
private String name
;
}
3.配置 JPA
spring.jpa.hibernate.ddl-auto=update //必要
spring.jpa.show-sql=true //可选 在日志中打印jpa相关信息
spring.jpa.hibernate.ddl-auto(后两个慎用)
update 每次运行程序,没有表格会新建表格,表内有数据不会清空,只会更新
validate 运行程序会校验数据与数据库的字段类型是否相同,不同会报错
creat 每次运行该程序,没有表格会新建表格,表内有数据会清空
create-drop 每次程序结束的时候会清空表
4.Dao
public interface UserDao extends JpaRepository<User,Integer> {
}
5.测试
当项目启动时将会自动创建表
控制台日志如下:
Hibernate: select user0_.id as id1_0_0_, user0_.name as name2_0_0_ from t_users user0_ where user0_.id=?
Hibernate: insert into t_users (name) values (?)
navicat查询数据库