使用Spring Data JPA如何通过连接多个实体来返回对象?

6

我有三个实体:EntityA,EntityB和EntityC。我需要使用Spring Data JPA从这些实体中通过连接查询获取值,并将其放入对象列表中。 查询如下:

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;  
}

实体C:

@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;    
}

我尝试了这样做。
@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);
  }

3
什么是问题?你尝试过什么? - Predrag Maric
2个回答

1
你只需要认识到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

0

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 数组作为 Object,你需要将其强制转换为 Array。
Object[] objArray = (Object[]) result_from_the_repositoryLayer;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接