According to the following article,
I18N data with hibernate, I'm implementing a usertype that access to an Hibernate style DAO to retrieve the code or the text of the loclalized label.
My usertype nullSafeGet and nullSafeSet methods are like this :
Code:
public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
throws HibernateException, SQLException {
String code = (String) Hibernate.STRING.nullSafeGet(rs, names);
return LocalizedLabelManager.getText(code, LocaleUtil.currentLocale());
}
Code:
public void nullSafeSet(PreparedStatement st, Object value, int index)
throws HibernateException, SQLException {
String code = LocalizedLabelManager.getCode( (String) value, LocaleUtil.currentLocale());
Hibernate.STRING.nullSafeSet(st, code, index);
}
My LocalizedLabelManager access a LocalizedLabelDao for the method getCode() :
Code:
public static String getCode(String text, Locale userLocale){
String code = localizedLabelDao.getCode(text, userLocale);
if(code == null){
code = generateCode(text, userLocale);
LocalizedLabel localizedLabel = new LocalizedLabel(userLocale, text);
localizedLabelDao.saveOrUpdate(localizedLabel);
}
return code;
}
And here is the getCode method of my LocalizedLabelDao:
Code:
public String getCode(String text, Locale locale) {
return (String) this.getSession().createQuery("from LocalizedLabel ll where ll.text = :text and ll.locale = :locale")
.setString("text", text)
.setLocale("locale", locale).setCacheable(true).uniqueResult();
}
A localizedLabel is a traditional POJO.
The problem is when I try to save an object that has a LocalizedLabel, like my Category object below :
Code:
@Entity
public class Category {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Type(type="LocalizedLabelUserType")
private String name;
@Type(type="LocalizedLabelUserType")
private String description;
@ManyToOne
private Category parent;
//Other methods are not relevant
}
I get the folowing exception :
Exception in thread "main" org.hibernate.AssertionFailure: null id in my.package.Category entry (don't flush the Session after an exception occurs)
Which is trown by the DefaultFlushEntityEventListener that check id's before it flushes the session before executing the query in getCode() method.
But it's normal that an id is null as, at the time of this query excution, the save operation on my category is pending.
Even if I understand that the session needs to be flushed before a query execution, is there a way to handle that issue? Is it bad design to access a DAO in a usertype (indeed, it sound weird) ?
Thanks in advance,
-Aymeric