使用 Spring Jpa 从两个或多个表中获取选定的列

Posted

技术标签:

【中文标题】使用 Spring Jpa 从两个或多个表中获取选定的列【英文标题】:Fetch selected columns from two or more table using Spring Jpa 【发布时间】:2019-02-18 03:31:22 【问题描述】:
@Entity
public class A
 //some properties



 @Entity
 public class B
  //Some properties
 

我想使用 JPA 从两个表中获取选定的列,我知道如何通过存储库和控制器获取单个实体表数据。

存储库:

public interface extends JPARepository<A, Long>
    List<A> findAll();

控制器:

public class class_name
@AutoWired
private JPARepository repo;
 @RequestMapping("/data")
public List<A> getData()
return repo.findAll();


以上代码是获取单表数据。现在,我想从两个表中获取选定的列。

Note: A, B Entities have mappings

【问题讨论】:

【参考方案1】:

您可以做的是在存储库中的一个方法上使用@Query 注释并执行如下操作:

public Name 
    String firstName;
    String telephone;

    public Name(String firstName,String telephon) 
        //initialize fields
    


@Query(select new dummy.Name(u.name,c.telephone) from User u join fetch u.contact c where u.externalId= ?1 )
public Name getName(String externalId)

您可以轻松返回 List 而不是使用构造函数查询,但我发现这种方式更简洁。

【讨论】:

在存储库中我需要传递哪个实体类

以上是关于使用 Spring Jpa 从两个或多个表中获取选定的列的主要内容,如果未能解决你的问题,请参考以下文章