Spring Data JPA 实现多表关联查询[通俗易懂]

Spring Data JPA 实现多表关联查询[通俗易懂]SpringDataJPA 的多表操作比较麻烦。下面通过文章与文章类别(多对多的关系)来介绍SpringDataJPA中的多表操作。代码实现jar包依赖和datasource配置这里就不贴了。实体类1、实体类Article.javaimportjava.io.Serializable;importjava.util.Date;impor…

大家好,又见面了,我是你们的朋友全栈君。

多表查询在spring data jpa中有两种实现方式,第一种是利用hibernate的级联查询来实现,第二种是创建一个结果集的接口来接收连表查询后的结果,这里介绍第二种方式。

一、一对一映射

实体 UserInfo :用户。

实体 Address:家庭住址。

这里通过外键的方式(一个实体通过外键关联到另一个实体的主键)来实现一对一关联。

实体类

1、实体类 UserInfo.java

package com.johnfnash.learn.domain;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="tb_user")
public class UserInfo implements Serializable { 
   
  private static final long serialVersionUID = 8283950216116626180L;

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long userId;
  private String name;
  private int age;
  private String sex;
  private String email;

  // 与 Address 的关联 
  private Long addressId;

  public UserInfo() {
    super();
  }

  public UserInfo(String name, int age, String sex, String email, Long addressId) {
    super();
    this.name = name;
    this.age = age;
    this.sex = sex;
    this.email = email;
    this.addressId = addressId;
  }

  // getter, setter

  @Override
  public String toString() {
    return String.format("UserInfo [userId=%d, name=%s, age=%s, sex=%s, email=%s]", userId, name, age, sex, email);
  }

}

2. 实体类 Address.java

package com.johnfnash.learn.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tb_address")
public class Address { 
   

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long addressId;
  private String areaCode;
  private String country;
  private String province;
  private String city;
  private String area;
  private String detailAddress;

  public Address() {
    super();
  }

  public Address(String areaCode, String country, String province, String city, String area,
      String detailAddress) {
    super();
    this.areaCode = areaCode;
    this.country = country;
    this.province = province;
    this.city = city;
    this.area = area;
    this.detailAddress = detailAddress;
  }

  // getter, setter

  @Override
  public String toString() {
    return "Address [addressId=" + addressId + ", areaCode=" + areaCode + ", country=" + country + ", province="
        + province + ", city=" + city + ", area=" + area + ", detailAddress=" + detailAddress + "]";
  }

}

Dao 层

1、UserInfoRepository.java

package com.johnfnash.learn.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import com.johnfnash.learn.domain.UserInfo;
import com.johnfnash.learn.domain.ViewInfo;

public interface UserInfoRepository extends JpaRepository<UserInfo, Long> {

  @Query(value = "SELECT new com.johnfnash.learn.domain.ViewInfo(u, a) FROM UserInfo u, Address a WHERE u.addressId = a.addressId")
  public List<ViewInfo> findViewInfo();

}

注:这里的 ViewInfo 类用来一个用来接收多表查询结果集的类(使用 new + 完整类名构造函数)
代码如下:

package com.johnfnash.learn.domain;

import java.io.Serializable;

public class ViewInfo implements Serializable { 
   

  private static final long serialVersionUID = -6347911007178390219L;

  private UserInfo userInfo;
  private Address address;

  public ViewInfo() {

  }

  public ViewInfo(UserInfo userInfo) {
    Address address = new Address();
    this.userInfo = userInfo;
    this.address = address;
  }

  public ViewInfo(Address address) {
    UserInfo userInfo = new UserInfo();
    this.userInfo = userInfo;
    this.address = address;
  }

  public ViewInfo(UserInfo userInfo, Address address) {
    this.userInfo = userInfo;
    this.address = address;
  }

  // getter, setter

}

2. AddressRepository.java

package com.johnfnash.learn.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.johnfnash.learn.domain.Address;

public interface AddressRepository extends JpaRepository<Address, Long> { 
   

}

测试代码

package com.johnfnash.learn;

import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.johnfnash.learn.domain.Address;
import com.johnfnash.learn.domain.UserInfo;
import com.johnfnash.learn.domain.ViewInfo;
import com.johnfnash.learn.repository.AddressRepository;
import com.johnfnash.learn.repository.UserInfoRepository;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserInfoRepositoryTests {

  @Autowired
    private UserInfoRepository userInfoRepository;

  @Autowired
  private AddressRepository addressRepository;

  @Before
    public void init() {
        Address addr1 = new Address("027","CN","HuBei", "WuHan","WuChang", "123 street");
        Address addr2 = new Address("023","CN","ChongQing", "ChongQing","YuBei", "123 road");
        addressRepository.save(addr1);
        addressRepository.save(addr2);

        UserInfo user1 = new UserInfo("ZS", 21,"Male","123@xx.com", addr1.getAddressId());
        UserInfo user2 = new UserInfo("Ww", 25,"Male","234@xx.com", addr2.getAddressId());
        userInfoRepository.save(user1);
        userInfoRepository.save(user2);
    }

  @After
  public void deleteAll() {
    userInfoRepository.deleteAll();

    addressRepository.deleteAll();
  }

  @Test
  public void testQuery() {
    List<ViewInfo> viewInfos = userInfoRepository.findViewInfo();
    for (ViewInfo viewInfo : viewInfos) {
      System.out.println(viewInfo.getUserInfo());
      System.out.println(viewInfo.getAddress());
    }
  }

}

查询相关的 sql 如下:

Hibernate: select userinfo0_.user_id as col_0_0_, address1_.address_id as col_1_0_ from tb_user userinfo0_ cross join tb_address address1_ where userinfo0_.address_id=address1_.address_id Hibernate: select userinfo0_.user_id as user_id1_4_0_, userinfo0_.address_id as address_2_4_0_, userinfo0_.age as age3_4_0_, userinfo0_.email as email4_4_0_, userinfo0_.name as name5_4_0_, userinfo0_.sex as sex6_4_0_ from tb_user userinfo0_ where userinfo0_.user_id=? Hibernate: select address0_.address_id as address_1_3_0_, address0_.area as area2_3_0_, address0_.area_code as area_cod3_3_0_, address0_.city as city4_3_0_, address0_.country as country5_3_0_, address0_.detail_address as detail_a6_3_0_, address0_.province as province7_3_0_ from tb_address address0_ where address0_.address_id=? Hibernate: select userinfo0_.user_id as user_id1_4_0_, userinfo0_.address_id as address_2_4_0_, userinfo0_.age as age3_4_0_, userinfo0_.email as email4_4_0_, userinfo0_.name as name5_4_0_, userinfo0_.sex as sex6_4_0_ from tb_user userinfo0_ where userinfo0_.user_id=? Hibernate: select address0_.address_id as address_1_3_0_, address0_.area as area2_3_0_, address0_.area_code as area_cod3_3_0_, address0_.city as city4_3_0_, address0_.country as country5_3_0_, address0_.detail_address as detail_a6_3_0_, address0_.province as province7_3_0_ from tb_address address0_ where address0_.address_id=? Hibernate: select userinfo0_.user_id as user_id1_4_, userinfo0_.address_id as address_2_4_, userinfo0_.age as age3_4_, userinfo0_.email as email4_4_, userinfo0_.name as name5_4_, userinfo0_.sex as sex6_4_ from tb_user userinfo0_ Hibernate: select address0_.address_id as address_1_3_, address0_.area as area2_3_, address0_.area_code as area_cod3_3_, address0_.city as city4_3_, address0_.country as country5_3_, address0_.detail_address as detail_a6_3_, address0_.province as province7_3_ from tb_address address0_

查询结果如下:

UserInfo [userId=1, name=ZS, age=21, sex=Male, email=123@xx.com]
Address [addressId=1, areaCode=027, country=CN, province=HuBei, city=WuHan, area=WuChang, detailAddress=123 street]
UserInfo [userId=2, name=Ww, age=25, sex=Male, email=234@xx.com]
Address [addressId=2, areaCode=023, country=CN, province=ChongQing, city=ChongQing, area=YuBei, detailAddress=123 road]

二、多对多映射

实体 Author :作者。

实体 Book :书籍

这里通过关联表的方式来实现多对多关联。

实体类

实体类:Author.java

package com.johnfnash.learn.domain;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Author implements Serializable { 
   

  private static final long serialVersionUID = 1227555837798655046L;

  @Id
    @GeneratedValue
    private Integer id;

    private String name;

  public Author() {
    super();
  }

  public Author(String name) {
    super();
    this.name = name;
  }

  // getter, setter

  @Override
    public String toString() {
        return String.format("Author [id=%s, name=%s]", id, name);
    }

}

Book.java 实体类

package com.johnfnash.learn.domain;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Book implements Serializable { 
   

  private static final long serialVersionUID = -2470510857424220408L;

  @Id
    @GeneratedValue
    private Integer id;

    private String name;

    public Book() {
        super();
    }

    public Book(String name) {
        super();
        this.name = name;
    }

  //getter, setter

  @Override
  public String toString() {
    return String.format("Book [id=%s, name=%s]", id, name);
  }

}

实体类BookAuthor.java

package com.johnfnash.learn.domain;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;

@Entity
@IdClass(BookAuthorPK.class)
@Table(name = "book_author")
public class BookAuthor { 
   

  @Id
  private Integer bookId;

  @Id
  private Integer authorId;

  public BookAuthor() {
    super();
  }

  public BookAuthor(Integer bookId, Integer authorId) {
    super();
    this.bookId = bookId;
    this.authorId = authorId;
  }

  // getter, setter

}

注:这里使用 @IdClass 注解指定一个联合主键类来映射实体类的多个属性。这个联合主键类的代码如下:

package com.johnfnash.learn.domain;

import java.io.Serializable;

public class BookAuthorPK implements Serializable { 
   

  private static final long serialVersionUID = -1158141803682305656L;

  private Integer bookId;

  private Integer authorId;

  public Integer getBookId() {
    return bookId;
  }

  public void setBookId(Integer bookId) {
    this.bookId = bookId;
  }

  public Integer getAuthorId() {
    return authorId;
  }

  public void setAuthorId(Integer authorId) {
    this.authorId = authorId;
  }

}

Dao 层

BookRepository.java

package com.johnfnash.learn.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import com.johnfnash.learn.domain.Book;

public interface BookRepository extends JpaRepository<Book, Integer> {

  @Query(nativeQuery = true, value = "SELECT b.id, b.name, GROUP_CONCAT(a.name) as authorName from book b, author a, book_author ba"
      + " where b.id = ba.book_id and a.id = ba.author_id and b.name like ?1 group by b.id, b.name")
    List<Object[]> findByNameContaining(String name);

}

注:
1)这里使用 nativeQuery = true 指定使用原生 SQL 进行查询(个人觉得复杂的查询使用原生SQL更好
2)这里使用了 mysql 的内置函数 GROUP_CONCAT 进行行转列, HQL 无法直接识别。可能会出现 Caused by: org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode 的错误

JpaRepository.java

package com.johnfnash.learn.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.johnfnash.learn.domain.Author;

public interface AuthorRepository extends JpaRepository<Author, Integer> { 
   

}

BookAuthorRepository.java

package com.johnfnash.learn.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.johnfnash.learn.domain.BookAuthor;

public interface BookAuthorRepository extends JpaRepository<BookAuthor, Integer> { 
   

}

测试代码

package com.johnfnash.learn;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.johnfnash.learn.domain.Author;
import com.johnfnash.learn.domain.Book;
import com.johnfnash.learn.domain.BookAuthor;
import com.johnfnash.learn.repository.AuthorRepository;
import com.johnfnash.learn.repository.BookAuthorRepository;
import com.johnfnash.learn.repository.BookRepository;

@RunWith(SpringRunner.class)
@SpringBootTest
public class BookRepositoryTests {

  @Autowired
  private BookRepository bookRepository;

  @Autowired
  private AuthorRepository authorRepository;

  @Autowired
  private BookAuthorRepository bookAuthorRepository;

  @Before
  public void init() {
      Author lewis = new Author("Lewis");
      Author mark = new Author("Mark");
      Author peter = new Author("Peter");
      authorRepository.save(lewis);
      authorRepository.save(mark);
      authorRepository.save(peter);

      Book spring = new Book("Spring in Action");
      Book springboot = new Book("Spring Boot in Action");
      bookRepository.save(spring);
      bookRepository.save(springboot);

      bookAuthorRepository.save(new BookAuthor(spring.getId(), lewis.getId()));
      bookAuthorRepository.save(new BookAuthor(spring.getId(), mark.getId()));
      bookAuthorRepository.save(new BookAuthor(springboot.getId(), mark.getId()));
      bookAuthorRepository.save(new BookAuthor(springboot.getId(), peter.getId()));
  }

  @After
  public void deleteAll() {
    bookAuthorRepository.deleteAll();
    bookRepository.deleteAll();
    authorRepository.deleteAll();
  }

  @Test
  public void findAll() {
    assertEquals(bookRepository.findAll().size(), 2);
    assertEquals(authorRepository.findAll().size(), 3);

    List<Object[]> books = bookRepository.findByNameContaining("Spring%");
    for (Object[] book : books) {
      for (Object object : book) {
        System.out.print(object + ", ");
      }
      System.out.println();
    }
  }

}

执行 findAll 方法后,查询的相关 SQL 如下:

Hibernate: SELECT b.id, b.name, GROUP_CONCAT(a.name) as authorName from book b, author a, book_author ba where b.id = ba.book_id and a.id = ba.author_id and b.name like ? group by b.id, b.name

输出的结果如下:

3652, Spring in Action, Lewis,Mark, 
3653, Spring Boot in Action, Mark,Peter, 

参考

(1) Spring Data JPA 实现多表关联查询

(2) springboot(五): spring data jpa的使用

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/132322.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • ubuntu下deb包安装方法_ubuntu安装下载文件

    ubuntu下deb包安装方法_ubuntu安装下载文件deb包是Debian,Ubuntu等Linux发行版的软件安装包,扩展名为.deb,是类似于rpm的软件包,Debian,Ubuntu系统不推荐使用deb软件包,因为要解决软件包依赖问题,安装也比较麻烦。如果Ubuntu要安装新软件,已有deb安装包(例如:linuxidc.deb),但是无法登录到桌面环境。那该怎么安装?答案是:使用dpkg命令。dpkg是Debianlinuxidc的简写,是为Debian专门开发的套件管理系统,方便软件的安装、更新及移除。所有源自Debian的Linux发行

    2022年10月20日
    0
  • pycharm多行代码同时注释、去除注释_vs如何统计代码行数

    pycharm多行代码同时注释、去除注释_vs如何统计代码行数使用pycharm编写Python脚本的时候,先选中需要注释的行,然后同时按键盘右下角的—-Ctrl和Ctrl键正上方的‘/’键—可以实现多行注释注意:1、只有在pycharm中编写Python代码(以.py结尾的文件)才能用此方法去多行注释2、在选中行的时候不管是全部选中,还是只选中了该行中的的部分代码,都能实现多行注释,如下图:注释前:注释后:…

    2022年8月28日
    2
  • magisk下载里显示没有模块_太极Magisk模块

    magisk下载里显示没有模块_太极Magisk模块太极Magisk模块是一款很多网友都在找的安卓模块更改工具,可以将普通版的免root模式的太极app升级成Magisk模式,操作也非常简单,感兴趣的朋友欢迎前来下载!太极Magisk模块功能1.太极完全支持Android9.0。2.太极能以免Root/免刷机模式运行。3.太极不影响全局。可以只对特定的应用开启Xposed功能,无需使用Xposed的APP运行起来就跟系统没有Xp…

    2022年5月23日
    305
  • linux objdump命令,Linux objdump命令

    linux objdump命令,Linux objdump命令一、简介objdump命令是用查看目标文件或者可执行的目标文件的构成的gcc工具。二、选项三、实例1)显示文件头信息objdump-ftest2)显示SectionHeader信息objdump-htest3)显示全部Header信息objdump-xtest4)显示全部Header信息,并显示对应的十六进制文件代码objdump-stest5)输出目标文件的符号表objdump…

    2022年10月30日
    0
  • 史上最简单的Hibernate入门简单介绍

    史上最简单的Hibernate入门简单介绍

    2021年12月9日
    38
  • CPU内核态和用户态的区别[通俗易懂]

    CPU内核态和用户态的区别[通俗易懂]内核态:cpu可以访问内存的所有数据,包括外围设备,例如硬盘,网卡,cpu也可以将自己从一个程序切换到另一个程序。用户态:只能受限的访问内存,且不允许访问外围设备,占用cpu的能力被剥夺,cpu资源可以被其他程序获取。指令划分特权指令:只能由操作系统使用、用户程序不能使用的指令。举例:启动I/O内存清零修改程序状态字设置时钟允许/禁止终端停机非特权指令:用户程序可以使用的指令。举例:控制转移算数运算取数指令访管指令(使用户程序从用户态陷入内核态)特权级别R0相当于.

    2022年9月17日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号