本文介绍了在Hiberate Criteria API中查询枚举方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 @Entity ,它有一个 @Enumerated 字段映射到它:

I have an @Entity which has an @Enumerated field mapped to it:

@Entity
@Table
public class Device implements Serializable {

    @Id
    @GeneratedValue
    private Long id;
    @Enumerated(EnumType.STRING)
    private DeviceType typeOfDevice;

    [....]

}

DeviceType 是典型的Java 5枚举:

DeviceType is a typical java 5 enum:

public enum DeviceType {
  MOBILE(true), EMAIL(false);
  private final boolean fubar;

  private DeviceType(boolean fubar) {
    this.fubar= fubar;
  }

  public boolean isFubar() {
    return fubar;
  }
}

我如何查询设备具有的实体typeOfDevice.isFubar()== true

return factory.getCurrentSession().createCriteria(Device.class).
       add(Restrictions.eq("typeOfDevice.isFubar", true)).list();

没有这样做:

return factory.getCurrentSession().createCriteria(Device.class).
       createCriteria("typeOfDevice").add(Restrictions.eq("fubar", true)).list();


推荐答案

以下行:

Criteria criteria = factory.getCurrentSession().createCriteria(Device.class);
Disjunction or = Restrictions.disjunction();

for (DeviceType type : DeviceType.values()) {
    if (type.isFubar()) {
        or.add(Restrictions.eq("typeOfDevice", type));
    }
}

criteria.add(or);

return criteria;

而不是执行其中typeOfDevice.fubar = true ,我们正在接近于其中(typeOfDevice = Mobile OR typeOfDevice = OtherFubar OR typeOfDevice = OtherOtherFubar)的行。我意识到这不是你最初拍摄的一线,但我认为这是问题的答案。

Instead of doing where typeOfDevice.fubar = true, we're approaching it more along the lines of where (typeOfDevice = Mobile OR typeOfDevice = OtherFubar OR typeOfDevice = OtherOtherFubar). I realize this isn't the one-liner you were originally shooting for, but I think it answers the question as asked.

这篇关于在Hiberate Criteria API中查询枚举方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-17 00:47