0%

jpa环境搭建

文章字数:249,阅读全文大约需要1分钟

搭建一个基础的jpa

依赖

pom.xml中加入依赖

1
2
3
4
5
6
7
8
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

model层

主要作用是和数据库映射的实体类

1
2
3
4
5
6
7
8
9
10
11
//用lombok或者自己写get和set
@Getter
@Setter
@Entity //标注给spring
public class User{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private String id;//id,自增
private String name;//其它属性自动关联

}

Dao

数据库操作,一个model对应一个Dao

1
2
3
4
//<实体类model,id类型>
public interface UserDao extends JpaRepository<User, String> {

}

继承之后基本的增删改查功能都具备了

配置

application.properties

1
2
3
4
5
6
7
8
9
10
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 每次运行创建新的表
spring.jpa.properties.hibernate.hbm2ddl.auto=create
# validate 每次运行时验证表结构
# create 每次新建
# create-drop 加载创建,退出删除
# update 追加更新