【问题标题】:Fetch selected columns from two or more table using Spring Jpa使用 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

【问题讨论】:

    标签: spring hibernate rest spring-boot spring-data-jpa


    【解决方案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 而不是使用构造函数查询,但我发现这种方式更简洁。

    【讨论】:

    • 在存储库中我需要传递哪个实体类
    猜你喜欢
    • 1970-01-01
    • 2014-05-04
    • 2017-10-08
    • 2017-04-12
    • 2014-04-16
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多