Spring Boot学习7——JPA

本文介绍了如何使用Spring Boot整合JPA,包括创建JPADemo项目,建立ORM实体类Comment和Article,创建自定义JpaRepository接口,配置数据源,以及进行测试。JPA作为Java持久化API,提供标准化的ORM支持,简化了数据库操作并具备强大的查询能力。
摘要由CSDN通过智能技术生成

JPA

  • JPA(Java Persistence API)Java持久化 API,是一套基于ORM思想的规范。
  • 优势
    1、标准化
    2、对容器级特性的支持
    3、简单易用,集成方便
    4、可媲美JDBC的查询能力
    5、支持面向对象的高级特性

使用Spring Boot整合JPA

一、创建项目JPADemo

在这里插入图片描述
在这里插入图片描述

二、创建对象关系映射(orm)实体类

创建评论实体类Comment

  • 创建bean子包
    在这里插入图片描述
package net.lj.lesson07.bean;

import javax.persistence.*;

/**
 * 评论实体类
 */
@Entity(name = "t_comment")//实体类注释,对应数据表
public class Comment {
    @Id//主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//填充值策略
    @Column(name = "id")//字段绑定
    private Integer id;
    @Column(name = "content")
    private String content;
    @Column(name = "author")
    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 +
                '}';
    }
}

创建文章实体类Article

在这里插入图片描述

package net.lj.lesson07.bean;

import javax.persistence.*;
import java.util.List;

/**
 * 文章实体类
 */
@Entity(name = "t_article") //实体注解
public class Article {
    @Id//主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//填充值策略
    @Column(name = "id") //绑定字段
    private Integer id;
    @Column(name = "title")
    private String title;
    @Column(name = "content")
    private String content;
    //查询时一并查询子表
    @OneToMany(fetch = FetchType.EAGER)//一对多
    @JoinTable(name = "t_comment",joinColumns = {@JoinColumn(name = "a_id")},
            inverseJoinColumns = {@JoinColumn(name = "id")})//关联表、关联字段、主键
    private List<Comment> commentList;

    public Integer getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

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

    public List<Comment> getCommentList() {
        return commentList;
    }

    public void setCommentList(List<Comment> commentList) {
        this.commentList = commentList;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", commentList=" + commentList +
                '}';
    }
}

三、创建自定义JpaRepository接口ArticleRepository

  • 创建repository子包
    在这里插入图片描述
package net.lj.lesson07.repository;


import net.lj.lesson07.bean.Article;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 文章仓库接口
 */
public interface ArticleRepository extends JpaRepository<Article,Integer> {
}

四、添加数据源依赖,配置数据源属性

在pom里添加依赖

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.6</version>
</dependency>

在全局配置文件里配置数据源

spring.datasource.url=jdbc:mysql://localhost:3306/blog?serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

spring.datasource.druid.max-active=100
spring.datasource.druid.min-idle=10
spring.datasource.druid.initial-size=20

五、编写测试方法

package net.lj.lesson07;

import net.lj.lesson07.bean.Article;
import net.lj.lesson07.repository.ArticleRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
class JpaDemoApplicationTests {
    @Autowired //注入文章仓库
    private ArticleRepository articleRepository;

    @Test//查询所有文章
    public void testFindAll(){
        //查询所有文章记录
        List<Article> articles = articleRepository.findAll();
        articles.forEach(article -> System.out.println(article));
    }

}

启动测试

在这里插入图片描述

JPA实现个性化操作

创建评论仓库接口CommentRepository

在这里插入图片描述

package net.lj.lesson07.repository;

import net.lj.lesson07.bean.Comment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
/**
 * 评论仓库接口
 */
public interface CommentRepository extends JpaRepository<Comment, Integer> {
    /**
     * 根据文章ID进行分页查询评论
     * nativeQuery = true 表示使用原生SQL语句,否则使用HQL语句
     * @param aId 查询条件字母(文章编号)
     * @param pageable 可分页对象,分页查询需要该参数
     * @return 返回page独享,包含page的相关信息及查询结果集
     */
    @Query(value = "select * from t_comment where a_id=?1",nativeQuery = true)
    Page<Comment> findCommentPagedByArticleId01(Integer aId, Pageable pageable);

    /**
     根据文章ID进行分页查询评论
     * 没有设置nativeQuery,使用HQL语句
     * @param aId
     * @param pageable
     * @return
     */
    @Query(value = "select c from t_comment c where c.aId=?1")
    Page<Comment> findCommentPagedByArticleId02(Integer aId, Pageable pageable);
}

创建测试类CommentTests

在这里插入图片描述

package net.lj.lesson07;

import net.lj.lesson07.bean.Comment;
import net.lj.lesson07.repository.CommentRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.List;

@SpringBootTest
public class CommentTests {

    @Autowired
    private CommentRepository commentRepository;

    @Test //采用原生SQL语句测试按文章编号分类查询评论
    public void testFindCommentPagedByArticleId01() {
        // 当前页面索引
        int pageIndex = 1;
        // 设置页面大小
        int pageSize = 2;//没页最多两条记录
        //设置排序方式为降序
        Sort.Direction sort = Sort.Direction.DESC;
        // 创建分页器(页面索引、页面大小、排序方式、排序字段)
        Pageable pageable = PageRequest.of(pageIndex, pageSize,sort,"id");
        // 查询文章编号为1的页面对象
        Page<Comment> page = commentRepository.findCommentPagedByArticleId01(1, pageable);
        // 获取页面对象里的评论列表
        List<Comment> comments = page.getContent();
        // 获取页索引
        int number = page.getNumber();
        // 获取总页数
        int totalPages = page.getTotalPages();
        System.out.println("当前页:" + (number + 1)); // 页索引加1才是页码
        System.out.println("总页数:" + totalPages);
        // 输出当前页全部评论
        for (Comment comment : comments) {
            System.out.println(comment);
        }
    }
}

启动测试

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值