JPA轻松上手

it2026-06-18  6

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: -AUTO 默认参数,主键由程序控制 -IDENTITY 主键由数据库生成,auto_increment -SEQUENCE 通过数据库的序列产生主键 -Table 提供特定的数据库产生主键 */ @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id",length = 32,nullable = true) //字段名,长度默认255,默认为null 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

/* 第一个参数:实体类的类型 第二个参数:实体类id的类型 */ 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查询数据库

最新回复(0)