Querying on enum's method in Hiberate Criteria API

前端 未结 2 1046
心在旅途
心在旅途 2020-12-19 23:46

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

@Entity
@Table
public class Device implements Serializable {

    @I         


        
相关标签:
2条回答
  • 2020-12-19 23:52

    You have anotated it as

    @Enumerated(EnumType.STRING)
    

    this will store the name of the enum. Your db column will have either "MOBILE" or "EMAIL" but not 'true' or 'false'. you can change your query to

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

    Its more reable isn't?

    0 讨论(0)
  • 2020-12-20 00:16

    It seems like a solution to your problem might be along the lines of:

    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;
    

    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.

    0 讨论(0)
提交回复
热议问题