@JPA
#1. Spring Date JPA 介绍
Spring Data 是Spring的一个子项目,旨在统一和简化各类型数据的持久化存储方式,而不拘泥于是关系型数据库还是NoSQL数据库。无论是哪种持久化存储方式,数据访问对象(Data Access Objects,DAO)都会提供对对象的增加、删除、修改和查询的方法,以及排序和分页方法等。 Spring Data 提供了基于这些层面的统一接口(如:CrudRepository、 PagingAndSortingRepository),以实现持久化的存储。
JPA(Java Persistence API)是Java的持久化API,用于对象的持久化。它是一个非常强大的ORM持久化的解决方案,免去了使用JDBCTemplate开发的编写脚本工作。JPA通过简单约定好接口方法的规则自动生成相应的JPQL语句,然后映射成POJO对象。
JPA是一个规范化接口,封装了Hibernate的操作作为默认实现,让用户不通过任何配置即可完成数据库的操作。
##2.配置环境
使用Maven管理包,使用springboot框架,建个空maven项目。
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-jpa com.alibaba druid-spring-boot-starter 1.1.23 com.oracle.ojdbc ojdbc8 runtime org.projectlombok lombok true
##3.aplication.yml的文档
spring:
datasource:
url: jdbc:mysql://localhost:3306/"自己的数据库"?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&autoReconnect=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: rootroot
##4.实体类与表的映射
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "b_comment")
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "content" )
private String content;
@Column(name = "author")
private String author;
@Column(name = "article_id")
private Integer articleId;
}
##5.自定义接口
import com.wukongnotnull.domain.Comment; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import javax.transaction.Transactional; import java.util.List; import java.util.Optional; // 记得添加该注解 @Repository @Repository public interface CommentRepository extends JpaRepository{ @Override List findAll(); @Override Optional findById(Integer id); // 查询条件:作者不为空 List findByAuthorNotNull(); @Override long count(); @Override S saveAndFlush(S s); // 不能使用 * 通配符 @Query("select c from b_comment c where c.articleId=?1",nativeQuery = false) ListgetCommentList(Integer articleId); // 若使用通配符 * @Query(value = "select * from b_comment c where c.articleId=?1",nativeQuery = true) List getCommentList2(Integer articleId); @Transactional @Modifying @Query(value = "update b_comment set author =?1 where id =?2 ",nativeQuery = true) int updateComment(String author,Integer id); @Transactional @Modifying @Query(value = "delete from b_comment where id = ?1",nativeQuery = true) int deleteComment(Integer id); @Override S save(S entity); }
##6.测试类
import com.wukongnotnull.domain.Comment;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CommentRepositoryTest {
@Autowired
private CommentRepository commentRepository;
@Test
void findAll() {
System.out.println(commentRepository.findAll());
}
@Test
void findById(){
Optional optionalComment = commentRepository.findById(1);
if (optionalComment.isPresent()) {
Comment comment1 = optionalComment.get();
System.out.println(comment1);
}
}
@Test
void findByAuthorNotNull(){
System.out.println(commentRepository.findByAuthorNotNull());
}
@Test
void count(){
System.out.println(commentRepository.count());
}
@Test
void getCommentList(){
System.out.println(commentRepository.getCommentList(1));
}
@Test
void getCommentList2(){
System.out.println(commentRepository.getCommentList2(1));
}
@Test
void updateComment(){
System.out.println(commentRepository.updateComment("6666", 6));
}
@Test
void deleteComment(){
System.out.println(commentRepository.deleteComment(6));
}
@Test
void save(){
Comment comment = new Comment();
comment.setAuthor("wukongnotnull0716");
comment.setContent("content .... wukong ...");
System.out.println(commentRepository.save(comment));
}
}
##7.JPA常用注解
| 注解 | 作用 | 常用属性 |
|---|---|---|
| @Data | 给实体类加get/set/toString/EqualsAndHashCode方法,是lombok的注解 | |
| @Entity | 指定当前类是实体类 | |
| @Table | 指定实体类和表之间的对应关系 | name:指定数据库表的名称 |
| @EntityListeners | 在实体类增删改的时候监听,为创建人/创建时间等基础字段赋值 | value:指定监听类 |
| @Id | 指定当前字段是主键 | |
| @SequenceGenerator | 指定数据库序列别名 | sequenceName:数据库序列名 |
| @GeneratedValue | 指定主键的生成方式 | strategy :指定主键生成策略generator:选择主键别名 |
| @Column | 指定实体类属性和数据库表之间的对应关系 | name:指定数据库表的列名称。unique:是否唯一 nullable:是否可以为空 nserttable:是否可以插入 updateable:是否可以更新 columnDefinition: 定义建表时创建此列的DDL |
| @CreatedBy | 自动插入创建人 | |
| @CreatedDate | 自动插入创建时间 | |
| @LastModifiedBy | 自动修改更新人 | |
| @LastModifiedDate | 自动修改更细时间 | |
| @Version | 自动更新版本号 | |
| @JsonFormat | 插入/修改/读取的时间转换成想要的格式 | pattern:展示格式 |



