您的位置:首页 > 编程语言 > Java开发

SpringBoot数据访问(二) SpringBoot整合JPA

2021-06-21 08:46 148 查看

JPA简介

Spring Data JPA是Spring Data大家族的一部分,它可以轻松实现基于JPA的存储库。该模块用于增强支持基于JPA的数据访问层,它使我们可以更加容易地构建使用数据访问技术的Spring驱动的应用程序。

对于普通的开发者而言,自己实现应用程序的数据访问层是一件很麻烦的时间,开发者必须编写大量样板代码来执行简单的查询以及执行分页和统计,Spring Data JPA旨在通过将工作量减少到实际需要的程度来显著改进数据访问层的实现。作为开发人员,我们只需要编写存储库接口(Repository接口),包括自定义查询方法,其余的工作,Spring将自动帮我们完成。

JPA特性

  • 对基于Spring和JPA的存储库构建的完善支持。
  • 支持Querydsl查询框架,从而支持类型安全的JPA查询。
  • 域类的透明审计。
  • 具备分页支持、动态查询执行、集成自定义数据访问代码的能力。
  • 在启动时验证带@Query注解的查询。
  • 支持基于XML的实体映射。
  • 通过引入@EnableJpaRepositories注解来实现基于JavaConfig的存储库配置。

SpringBoot整合JPA

(1)添加Spring Data JPA依赖启动器

 

引入这两个依赖器创建项目,在项目pom.xml文件会出现以下依赖:

(2)编写ORM实体类

package com.hardy.springbootdatajpa.entity;

import javax.persistence.*;

/**
* @Author: HardyYao
* @Date: 2021/6/13
*/
@Entity(name = "t_comment") // 设置ORM实体类,并指定映射的表名
public class Comment {

@Id // 映射对应的主键id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 设置主键自增策略
private Integer id;

private String content;

private String author;

@Column(name = "a_id")  // 指定映射的表字段名
private Integer aId;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

public Integer getaId() {
return aId;
}

public void setaId(Integer aId) {
this.aId = aId;
}

@Override
public String toString() {
return "Comment{" +
"id=" + id +
", content='" + content + '\'' +
", author='" + author + '\'' +
", aId=" + aId +
'}';
}
}

(3)编写Repository接口

package com.hardy.springbootdatajpa.repository;

import com.hardy.springbootdatajpa.entity.Comment;
import org.springframework.data.jpa.repository.JpaRepository;

/**
* @Author: HardyYao
* @Date: 2021/6/13
*/
public interface CommentRepository extends JpaRepository<Comment,Integer> {

}

(4)编写配置文件

# MySQL数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

(5)测试

编写测试方法:

package com.hardy.springbootdatajpa;

import com.hardy.springbootdatajpa.entity.Comment;
import com.hardy.springbootdatajpa.repository.CommentRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Optional;

@SpringBootTest
class SpringbootdataJpaApplicationTests {

@Autowired
private CommentRepository repository;

@Test
public void selectComment() {
Optional<Comment> optional = repository.findById(1);
if (optional.isPresent()) {
System.out.println(optional.get());
}
System.out.println();
}

}

打印测试结果:

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: