wah*_*cse 6 hibernate jpa spring-data-jpa
我有三个实体: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
Run Code Online (Sandbox Code Playgroud)
这些实体是:
实体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;
}
Run Code Online (Sandbox Code Playgroud)
实体B:
@Entity
public class EntityB {
@Id
@GeneratedValue
private Integer id;
private double testScore;
@OneToOne
@JoinColumn(name = "EntityA_id")
private EntityA a;
}
Run Code Online (Sandbox Code Playgroud)
实体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;
}
Run Code Online (Sandbox Code Playgroud)
我试过这样
@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);
}
Run Code Online (Sandbox Code Playgroud)
您只需要认识到 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10562 次 |
| 最近记录: |