Hibernate 如何使用spring数据jpa通过连接从多个实体返回对象?

Hibernate 如何使用spring数据jpa通过连接从多个实体返回对象?,hibernate,jpa,spring-data-jpa,Hibernate,Jpa,Spring Data Jpa,我有三个实体:EntityA、EntityB和EntityC。 从这些实体中,我需要通过使用SpringDataJPA将查询连接到对象列表中来获取值。 查询是: select x.id,x.formNo,x.name, z.testScore, y.semester from EntityA as x left join EntityB as z on x.id = z.a_id inner join EntityC as y on x.c_id = y.id where x

我有三个实体:EntityA、EntityB和EntityC。 从这些实体中,我需要通过使用SpringDataJPA将查询连接到对象列表中来获取值。 查询是:

select x.id,x.formNo,x.name, z.testScore, y.semester 
   from  EntityA as x left join EntityB as z on x.id = z.a_id 
    inner join EntityC as y on x.c_id = y.id where x.id=1
这些实体是:

实体A:

  @Entity
  public class EntityA {        
    @Id
    @GeneratedValue
    private Integer id;         
    private String name;        
    private String formNo;

    @OneToOne(mappedBy = "a",fetch=FetchType.LAZY, cascade = CascadeType.REMOVE)    
    private EntityB b;

    @ManyToOne
    @JoinColumn(name = "EntityC_id")
    private EntityC c;
}
实体B:

@Entity
public class EntityB {

@Id
@GeneratedValue
private Integer id;     
private double testScore;

@OneToOne
@JoinColumn(name = "EntityA_id")
private EntityA a;  
}
实体:

@Entity
public class EntityC {
@Id
@GeneratedValue
private Integer id;     
private String semester;

@OneToMany(mappedBy = "c",fetch=FetchType.LAZY, cascade = CascadeType.REMOVE)
private List<EntityA> a;    
}
@实体
公共类实体{
@身份证
@生成值
私有整数id;
私人字符串学期;
@OneToMany(mappedBy=“c”,fetch=FetchType.LAZY,cascade=CascadeType.REMOVE)
私人名单a;
}
我试过这样做

@Repository
public interface SomeObjectRepository extends JpaRepository<Object, Integer>{   
public final static String FIND_WITH_QUERY 
    = "select x.id,x.formNo,x.name, z.testScore, y.semester 
   from  EntityA as x left join EntityB as z on x.id = z.a_id 
    inner join EntityC as y on x.c_id = y.id where x.id=:id";

    @Query(FIND_WITH_QUERY)
    public List<Object> getObjects(@Param("id") String id);
  }
@存储库
公共接口SomeObjectRepository扩展了JpaRepository{
公共最终静态字符串FIND_WITH_查询
=“选择x.id、x.formNo、x.name、z.testScore、y.Serm
从EntityA作为x左连接EntityB作为x.id=z.a\U id上的z
在x.c_id=y.id上作为y的内部联接实体,其中x.id=:id“;
@查询(使用查询查找)
公共列表getObjects(@Param(“id”)字符串id);
}

您只需要认识到JPQL与SQL是不同的语言,并学习它。JPQL从不使用表名和列名。JPQL联接依赖于实体之间的关联,而不是依赖于
on
子句

因此,查询应该是简单的

select x.id,x.formNo,x.name, z.testScore, y.semester
from EntityA x 
left join x.b z
inner join x.c y
where x.id = :id

JPQL是一种与SQL 如果您不熟悉,可以使用原始SQL查询 我们调用本机查询

将此行添加到@Query,如下所示
nativeQuery=true

@Repository
public interface SomeObjectRepository extends JpaRepository<Object, Integer>{   
public final static String FIND_WITH_QUERY 
    = "select x.id,x.formNo,x.name, z.testScore, y.semester 
   from  EntityA as x left join EntityB as z on x.id = z.a_id 
    inner join EntityC as y on x.c_id = y.id where x.id=:id";

    @Query(FIND_WITH_QUERY,nativeQuery = true)
    public List<Object> getObjects(@Param("id") String id);
  }

问题是什么?你试过什么?
Object[] objArray = (Object[]) result_from_the_repositoryLayer;