我之前在写项目的时候,学习使用JPA进行数据库的操作,现在总结学习一下
1.在pom.xml中引入jpa的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2.在application.properties配置文件中进行数据库的相关配置
#dataSourse
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/library?charset=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
#jpa
spring.jpa.show-sql=true
3.创建与数据库表对应的实体类
添加@javax.persistence.Entity注解,说明这个 class 是实体类,并且使用默认的 ORM 规则,即 class 名即数据库表中表名,class 字段名即表中的字段名。但是必须与@javax.persistence.Id注解 结合使用,否则报错 No identifier specified for entity.
如果没有 @javax.persistence.Entity 和 @javax.persistence.Id 这两个注解的话,它完全就是一个典型的 POJO 的 Java 类,现在加上这两个注解之后,就可以作为一个实体类与数据库中的表相对应。
package com.example.test.entity;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.util.Date;
@Data
@Entity
public class BookInfo {
@Id
private Integer id;
private String name;
private Integer authorId;
private String publisher;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date publishDate;
private BigDecimal price;
private String description;
private Integer kindId;
private Integer state;
private Integer status;
}
此处再解释一下@Data注解,该注解可以为我们免去写get,set,toString等方法的烦恼,使用起来很方便,但是要安装插件后并引入依赖才能使用。
4.创建接口并继承JpaRepository<T, ID>接口,T表示与数据库表对应的实体类,ID表示该实体类主键的类型
package com.example.test.repository;
import com.example.test.entity.BookInfo;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TestRepository extends JpaRepository<BookInfo,Integer> {
}







网友评论