JPA HQL查询FK列的where条件

时间:2013-07-04 07:04:17

标签: hibernate jpa hql

我有两个实体关系:

@Entity
public class Project {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;


@OneToMany(mappedBy="project",cascade=CascadeType.ALL)
private java.util.List<RmtService> services = new ArrayList<RmtService>();

}

@javax.persistence.Entity
public class Service implements Serializable{

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;

@ManyToOne
    @JoinColumn(name = "project_id")
private Project project;

    // . . .
 }  

有一种方法可以执行生成SQL查询的JPA查询,如:

select * from service where project_id=?

...

我尝试过的所有查询都会在Project表上生成一个连接。

我试过了:

select s from Service s left join fetch s.project pp where pp.id = :id 

生成

select rmtservice0_.id as id1_1_0_, project1_.id as id1_0_1_, 
rmtservice0_.project_id as project3_1_0_, rmtservice0_.serviceType 
as serviceT2_1_0_, project1_.name as name2_0_1_, project1_.surname
as surname3_0_1_ from RmtService rmtservice0_ 
left outer join Project project1_ on rmtservice0_.project_id=project1_.id 
where   project1_.id=? 

select s from RmtService s where s.project.id = :id

生成2个查询:

select rmtservice0_.id as id1_1_, rmtservice0_.project_id as project3_1_, 
rmtservice0_.serviceType as serviceT2_1_ from RmtService rmtservice0_ where 
rmtservice0_.project_id=?

select project0_.id as id1_0_0_, project0_.name as name2_0_0_, project0_.surname
as surname3_0_0_ from Project project0_ where project0_.id=?

非常感谢

1 个答案:

答案 0 :(得分:1)

SELECT s FROM Service s
WHERE s.project = :project