我有三个实体:EntityA,EntityB和EntityC。 从那些实体我需要通过使用spring数据jpa从Joining 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=1
实体是:
EntityA:
@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;
}
EntityB:
@Entity
public class EntityB {
@Id
@GeneratedValue
private Integer id;
private double testScore;
@OneToOne
@JoinColumn(name = "EntityA_id")
private EntityA a;
}
EntityC:
@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);
}
答案 0 :(得分: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
答案 1 :(得分:0)
JPQL 是一种与 SQL 不同的语言 如果您不熟悉,可以使用原始 SQL 查询 我们调用Native Query
添加这一行到@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;