2015-02-09 46 views
5

我有三个实体:EntityA,EntityB和EntityC。 从这些实体我需要通过使用弹簧数据jpa从连接查询中获取值到对象列表中。 查询:如何通过使用弹簧数据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 

的实体是:

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); 
    } 
+2

问题是什么?你有什么尝试? – 2015-02-09 13:42:31

回答

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 
相关问题