CustomEntityHome. Possibly helpful
pdhaigh Nov 18, 2009 11:31 AMBelow is an extended EntityHome class that we find regularly useful. It provides the following convenience additions:
- Overrideable placeholders for code to be run pre-update or pre-persist (e.g. to set an
updatedBy
field) without having to replicate the update/persist methods - Catches and logs validation failures on persist
- Allows calling of persistNoMessage() to suppress the facesMessages for that transaction. Same for update
- Prevents spurious entityNotFound exceptions being logged when accessing non-existent entity.
public class CustomEntityHome<E> extends EntityHome<E>
{
private static final long serialVersionUID = 1L;
@Logger
private Log log;
private Boolean showMessages = true;
@Transactional
public void prePersist()
{
}
@Transactional
public void preUpdate()
{
}
@Transactional
public void preRemove()
{
}
@Override
protected void initInstance()
{
try
{
super.initInstance();
}
catch (EntityNotFoundException e)
{
// This is optional - you might have a hard-coded not found page, or client editable.
// FacesMessages.instance().add(StatusMessage.Severity.WARN,"Sorry, the page you were looking for was not found.");
super.setId(null);
Redirect.instance().setViewId(Constants.PAGE_NOT_FOUND_VIEW_ID);
Redirect.instance().execute();
}
}
@Override
@Transactional
public String persist()
{
prePersist();
try
{
getEntityManager().persist( getInstance() );
getEntityManager().flush();
assignId( PersistenceProvider.instance().getId( getInstance(), getEntityManager() ) );
if (this.showMessages) createdMessage();
raiseAfterTransactionSuccessEvent();
return "persisted";
}
catch (InvalidStateException ve)
{
log.warn("Caught validation failure",ve);
for (InvalidValue invalidValue : ve.getInvalidValues())
{
log.warn(invalidValue.toString());
}
throw ve;
}
}
@Override
@Transactional
public String update()
{
preUpdate();
joinTransaction();
getEntityManager().flush();
if (this.showMessages) updatedMessage();
raiseAfterTransactionSuccessEvent();
return "updated";
}
@Override
@Transactional
public String remove()
{
preRemove();
getEntityManager().remove( getInstance() );
getEntityManager().flush();
if (this.showMessages) deletedMessage();
raiseAfterTransactionSuccessEvent();
return "removed";
}
@Transactional
public String persistNoMessage()
{
showMessages = false;
String result = persist();
showMessages = true;
return result;
}
@Transactional
public String updateNoMessage()
{
showMessages = false;
String result = update();
showMessages = true;
return result;
}
@Transactional
public String removeNoMessage()
{
showMessages = false;
String result = remove();
showMessages = true;
return result;
}
public Boolean getShowMessages()
{
return showMessages;
}
public void setShowMessages(Boolean showMessages)
{
this.showMessages = showMessages;
}
}