简体   繁体   中英

Hibernate Like Criteria on Enum field

Given a Hibernate Entity Foo

@Entity
@Table(name = "foo")
class Foo {
    //ID Field

    @Column(name = "bar", nullable = false)
    @Enumerated(EnumType.STRING)
    private Bar bar;

    //Getters, Setters
}

And an Enum Bar

enum Bar {
    CAT,
    CRADLE,
    SILVER,
    SPOON;
}

I would like to run a query checking if Foo.bar's value contains some String matchString = "ADL".

Currently, my DetachedCriteria object is constructed as:

DetachedCriteria.forClass(Foo.class)
    .add(Restrictions.like("bar", matchString, MatchMode.ANYWHERE));`

but causes a java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Enum when invoked.

A query like this would only be possible if the enum is persisted using the String value rather than the ordinal - but even then I would not expect the criteria API to necessarily support a like for enums.

Instead of trying to do the like at the database level you can find all the enums where the name contains "bar" (in Java code) and then query for all the matches where "bar" is in that set. This is similar to https://stackoverflow.com/a/18899529/4248600 .

Disjunction or = Restrictions.disjunction();
for (BarEnum bar : BarEnum.values()) {
    if (bar.name().contains(matchStr)) {
        or.add(Restrictions.eq("bar", bar));
    }
}
criteria.add(or);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM