JPA CriteriaBuilder加入额外的ON子句参数(谓词)

时间:2013-02-04 17:09:02

标签: java sql jpa

如何加入额外的ON子句参数? 我有一个SQL:

select * from Address address left outer join  AddressLine line 
              on line.id = address.lineId AND line.type = 'MA'
where address.id = 1;

我有代码:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<AddressResult> query = cb.createQuery(AddressResult.class);
Root<Address> r = query.from(Address.class);
Join<Address, AddressLineMA >linesMA= r.join(Address_.linesMajor, JoinType.LEFT);

从数据库中获取数据。 这个查询没有按预期工作我得到这样的SQL:

select * from Address address left outer join  AddressLine line 
              on line.id = address.lineId 
    where address.id = 1;

AND line.type ='MA'缺失。有人知道如何解决这个问题吗?

我的AddressLineMA.class看起来像这样:

@Entity
@DiscriminatorValue(value = "MA")
public class AddressLineMA extends AddressLine {

}
@Entity
@Table(name = "AddressLine")
@DiscriminatorColumn(name = "TYPE", discriminatorType = DiscriminatorType.STRING)
public abstract class AddressLine {
   private Long id;
   private String type;
   private String line;
}

1 个答案:

答案 0 :(得分:4)

默认情况下,JPA查询始终返回所有子类。因此,如果只需要AddressLineMA实例,则必须将查询和关系更改为AddressLineMA而不是继承根类AddressLine。

如果要排除其他AddressLineMA子类,则可以使用添加到JPA 2.0的TYPE运算符:

   query.where(cb.equal(linesMA.type(), package.AddressLineMA.class));

不幸的是,仅在尚未发布的JPA 2.1规范中支持将其添加到ON子句中:

   linesMA.on(cb.equal(linesMA.type(), package.AddressLineMA.class));