我有一个映射到它@Entity的@Enumerated字段:
@Entity
@Enumerated
@Entity @Table public class Device implements Serializable { @Id @GeneratedValue private Long id; @Enumerated(EnumType.STRING) private DeviceType typeOfDevice; [....] }
DeviceType 是典型的Java 5枚举:
DeviceType
public enum DeviceType { MOBILE(true), EMAIL(false); private final boolean fubar; private DeviceType(boolean fubar) { this.fubar= fubar; } public boolean isFubar() { return fubar; } }
如何查询具有的Device实体typeOfDevice.isFubar() == true?
Device
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;
除了采取行动外where typeOfDevice.fubar = true,我们更遵循的方针where (typeOfDevice = Mobile OR typeOfDevice = OtherFubar OR typeOfDevice = OtherOtherFubar)。我意识到这并不是您最初拍摄的那种单线,但我认为它可以回答所问的问题。
where typeOfDevice.fubar = true
where (typeOfDevice = Mobile OR typeOfDevice = OtherFubar OR typeOfDevice = OtherOtherFubar)