This blog is mainly about Java...

Thursday, August 20, 2009

Using Enum in your entity beans

It is quite handy to use an Enum, especially with type String. This means that the enum will be translated as a text field in your database.

Imagine the following Entity Simple.java:
@Entity
public class Simple {
Process process;

@Enumerated(EnumType.STRING)
public void Process getProcess() {
return process;
}
}

And Process.java:
public enum Process {
WHAT,
THE,
BUCK
}


Now, I initally thought, that since you are defining the enum type to be string, then you can simply query the database using string as well like this:
entityManager.createQuery("from Simple s where s.process=:process").setParameter("process","WHAT").getResultList();
However this doesn't work. You will need to use an Enum type. So the solution is to use Enum.valueOf()
entityManager.createQuery("from Simple s where s.process=:process").setParameter("process",Process.valueOf("WHAT")).getResultList();

Now the query will run and return your list :-)

No comments:

Labels