Hi all,
I have posted this question on StackOverflow as well, I hope this "double post" is not a problem for you.
Today I defined an entity containing a set of enums. Instead of a oneToMany collection, I used a
CollectionOfElements since I wanted to reference the Java enums directly rather than wrappers.
The class (including Hibernate annotations) looks like:
Code:
@Entity
@Table(name = "MY_TABLE")
public class MyClass implements Serializable {
@Id @NotNull
@Column(name = "ID")
private Long id;
@Column(name = "NAME", nullable = false)
private String name;
@CollectionOfElements(fetch = FetchType.LAZY)
@JoinTable(name="MY_TABLE_ENUMS",joinColumns = @JoinColumn(name="TABLE_ID"))
@Column(name = "ENUM", nullable = false)
@Enumerated(EnumType.STRING)
private Set<MyEnum> enums;
// Setters and getters skipped...
}
And MyEnum is a normal Java enum without Hibernate annotations:
Code:
public enum MyEnum {
VALUE_A,
VALUE_B,
VALUE_C,
VALUE_D
}
This setup requires 2 DB tables, one for the entities (MY_TABLE) and a second one for the enums (MY_TABLE_ENUMS). Both tables have 2 columns: ID and NAME the first, TABLE_ID and ENUM the second (where TABLE_ID references rows in the first table).
I manually entered some objects in the DB (this DAO is meant for reading only, not for writing) and I tried to load MyClass instaces from the DB using
Code:
public List<MyClass> loadAll() {
return getSession().createCriteria(MyClass.class).list();
}
Everything worked as expected. The MyClass objects were returned along with the MyEnums in the set.
Then I extended my DAO, returning only MyClasses having a given value in the set:
Code:
public List<MyClass> loadForEnum(MyEnum myEnum) {
Query query = getSession().createQuery("from MyClass as mc inner join " +
"mc.enums as e where e = :myEnum");
query.setParameter("myEnum", myEnum);
return query.list();
}
Even though the loadForEnum method works fine, I don't like how it is written. Every other attempt I tried failed.
Does anyone know whether it is possible to achieve somethings similar without HQL, maybe using Criteria only?
Thanks a lot Andrea