JPQL没有条件

时间:2014-01-05 00:47:35

标签: sql hibernate jpa

我有EmployeeParkingSpace个实体的一对一关系,其中parkingId设置为@OneToOne,并且可选择员工,并在ParkingSpace实体中设置mappedBy

ParkingSpace并非必须

Employee,在分配时,parkingId将被设置

现在我想编写一个JPA QL来查找尚未分配的停车位列表。

我从

开始
@Entity
@Table(name="PARKING_SPACE")
@NamedQueries

({
@NamedQuery(name="ParkingSpace.findAllavailableInLocation",

query="select p from ParkingSpace p where p.emp IS NULL and p.location = :location")

})

public class ParkingSpace {

    @SequenceGenerator(name = "PARKING_ID_GENERATOR", 

            sequenceName = "PARKING_SEQ" ,initialValue=10 ,allocationSize=1)
    @Id

    @GeneratedValue(generator = "PARKING_ID_GENERATOR")

    private int id;


    @OneToOne(mappedBy="parking")

    private Employee emp;

但是hibernate 4.3正在生成查询

19:29:58.654 [main] DEBUG org.hibernate.SQL -

select parkingspa0_.id as id1_3_, parkingspa0_.location as location2_3_, parkingspa0_.lot as lot3_3_ 

from PARKING_SPACE parkingspa0_ where 
(parkingspa0_.id is null) and parkingspa0_.location=?

它忽略了ParkingSpace对象中的emp字段并转到id字段。

我试过p.em​​p.id在JPA QL中为null,它生成为

select parkingspa0_.id as id1_3_, parkingspa0_.location as location2_3_,
 parkingspa0_.lot as lot3_3_
 from PARKING_SPACE parkingspa0_ cross join Employee employee1_
 where parkingspa0_.id=employee1_.PSPACE_ID and (employee1_.id is null) and parkingspa0_.location=?

虽然我想要的是

select * from parking_space where id not in (select pspace_id from employee);

我能理解第二个问题,因为我要求p.emp.id为null,它会产生我想要的条件。但它不会解决问题,并且始终不会返回任何行 因为将没有没有身份证的员工作为其PKEY

我在这里缺少什么?我只是想要没有分配给员工的停车位。

2 个答案:

答案 0 :(得分:0)

jpql应该是:

select p from ParkingSpace p
  where p.emp.pspace_id not in :pspace_id

// pspace_id should be the mapped field of the Employee class

从EntityManager创建命名查询时,它将如下所示。

List<Long> pspaceIdList; // has some value
return em.createNamedQuery("ParkingSpace.findAllavailableInLocation")
  .setParameter("pspace_id", pspaceIdList)
  .getResultList();

答案 1 :(得分:0)

我在JPA QL以下工作。

从ParkingSpace p中选择p,其中p.id NOT IN(从员工e中选择e.parking.id)

eclipse链接至少在正确的方向上考虑员工也在查询中。但是hibernate完全错过了它: - )

VAM