JPA(Java Persistence API)定义了一系列对象持久化的标准,目前实现这一规范的产品有Hibernate、TopLink等。
引入依赖
在pom中把数据库驱动和jpa的依赖引入
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
在application.yml文件中加入配置信息
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.2.104/sell?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
jpa:
show-sql: true
hibernate:
ddl-auto: update
spring.jpa.hibernate.ddl-auto,用来自动建表,共有四种模式:
- update: 每次启动项目的时候,jpa都会检测一次数据库,如果没有这张表,那么就会新建;如果有的话,则只是更新这张表,表内的数据不会变;
- create: 和update类似,只不过表内的原有数据会在启动的时候被清空;
- create-drop: 和create类似,只不过是每次项目关闭的时候清空数据;
- validate: 启动项目的时候会对数据库字段类型和数据进行校验,如果没有问题,正常启动,有问题的话,会报错。
创建实体类
@Entity
@DynamicUpdate
public class ProductCategory {
@Id
@GeneratedValue
private Integer categoryId;
private String categoryName;
}
- @Entity定义对象将会成为被JPA管理的实体,将映射到指定的数据库表。只有一个属性name,表示其所对应的数据库中的表名。
- @Table指定数据库的表名。当实体类与其映射的数据库表名不同名时需要使用 @Table注解说明。
- @Id定义属性为数据库的主键,一个实体里面必须有一个。
- @GeneratedValue为主键生成策略。
- @DynamicUpdate:只更新实体中修改的列。不使用@DynamicUpdate时,即使没有改变的字段也会被更新,而且当执行更新操作时,如果对象的某个属性没有传入,那么数据库中这条数据的这个字段值为null。
创建Jpa接口
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
}
在JPA中有一个类名解析器,所以将类名按照一定规则进行命名,就可以解析出你想要的SQL语句。
- findAll(),查询全部的信息。
- findOne(id),根据id查询信息。
- By,条件查询
- In, 参数为集合类型
例子,持续更新:
List<ProductCategory> findByCategoryTypeIn(List<Integer> categoryTypeList);
List<ProductInfo> findByProductStatus(Integer productStatus);
本文介绍了JPA(Java Persistence API)的基础用法,包括如何引入依赖、配置数据库设置,以及创建实体类和JPA接口。在配置中提到了`spring.jpa.hibernate.ddl-auto`的不同模式,用于自动建表和数据处理。接着,讨论了实体类的注解,如@Entity、@Table、@Id和@GeneratedValue。最后,概述了JPA接口中的常用方法,如findAll、findOne和条件查询。

1770

被折叠的 条评论
为什么被折叠?



