Hi all,
I'm using Seam 2.0.0.GA and Hibernate 3.3.1.GA / Hibernate Validator 3.1.0.GA. Persistent objects are annotated POJOs.
My persistent object looks like:
Code:
@Table(...)
class MyTable {
String myField;
@Column(...)
@Length(max=3)
public String getMyField() { return myField; }
...
}
When persisting/updating, Hibernate Validator are correctly applied, so that the following code raises an InvalidStateException because the 'myField' field is limited to 3 characters:
Code:
MyTable myTable = new MyTable();
myTable.setMyField("foo bar foo bar foo bar foo bar");
entityManager.persist(myTable);
However, when I'm doing the following query, a JDBC exception is raised because the length constraint is violated in the database:
Code:
MyTable myTable = (MyTable)entityManager.
createQuery("select p from MyTable p where p.myField=:myField").
setParameter("myField", "foo bar foo bar foo bar").getSingleResult();
According to the documentation, this is the correct behavior, the Hibernate validators being applied only for insert/update queries.
So this is the question: is it possible to enable Hibernate validator also for SELECT query parameters ?
i.e. in the above query, I'm expecting an "InvalidStateException: field MyTable.myField is limited to 3 characters" exception.
Currently, my solution is to check the parameter before the SELECT query is done:
Code:
String param = "foo bar foo bar foo bar foo bar";
int maxLen = MyTable.class.getDeclaredMethod("getMyField").getAnnotation(Length.class).max();
if (param.length()>maxLen) {
throw new IllegalArgumentException("max len is "+maxLen);
}
MyTable myTable = (MyTable)entityManager.
createQuery("select p from MyTable p where p.myField=:myField").
setParameter("myField", param).getSingleResult();
However, this solution is neither elegant, nor reusable. So it would be great if Hibernate would validate the parameters for me.
Does such feature exist?
Thanks,
Julien