HibernateEntityConverter
patrickr Apr 24, 2007 12:46 PMThe EntityConverter doesn't seem to work with Hibernate managed sessions, does it? Because I didn?t find a HibernateEntityConverter either, I quickly wrote one myself. Maybe someone finds this useful. Feel free to add it to the source repository.
/**
* This implementation of the EntityConverter is suitable for any Hibernate
* Entity which uses annotations
*
* @author Patrick Ruhkopf
*/
@Name("org.jboss.seam.ui.hibernateEntityConverter")
@Scope(ScopeType.CONVERSATION)
@Install(precedence = BUILT_IN)
@Converter
@Intercept(NEVER)
public class HibernateEntityConverter extends EntityConverter
{
private ValueBinding<Session> session;
private Log log = Logging.getLog(HibernateEntityConverter.class);
public void setSession(ValueBinding<Session> session) {
this.session = session;
}
private Session getSession()
{
if (session==null) {
return (Session) Component.getInstance( "database" );
}
else {
return session.getValue();
}
}
@Override
protected Object loadEntityFromPersistenceContext(Class clazz, Object id)
{
if (id == null || clazz == null) {
return null;
}
if (id instanceof Serializable)
{
Serializable sid = (Serializable) id;
Object entity = null;
if (getSession() == null)
{
sessionNotFoundMessage();
}
entity = getSession().get(clazz, sid);
if (entity == null)
{
invalidSelectionMessage(clazz, id);
return null;
}
else
{
return entity;
}
} else {
log.error("Converter only supports serializable ids");
throw new ConverterException(FacesMessages.createFacesMessage(SEVERITY_ERROR,
getErrorMessageKey(), getErrorMessage()));
}
}
protected void sessionNotFoundMessage()
{
log.error("Hibernate session not found");
throw new ConverterException(FacesMessages.createFacesMessage(SEVERITY_ERROR,
getErrorMessageKey(), getErrorMessage()));
}
}
Taglib
<tag> <tag-name>convertHibernateEntity</tag-name> <converter> <converter-id>org.jboss.seam.ui.hibernateEntityConverter</converter-id> </converter> </tag>
Example of components.xml if your managed Hibernate session has a different name than database
<core:managed-hibernate-session name="myVeryDatabase"
auto-create="true"/>
<component name="org.jboss.seam.ui.hibernateEntityConverter">
<property name="session">#{myVeryDatabase}</property>
</component>
Regards
Patrick