This is a suggestion related to
http://www.hibernate.org/116.html#A11.
What about having an "unsaved-value" value like "table-look" to look in the corresponding entity table and see if a record wih the corresponding PK exists in the db when using saveOrUpdate() ? This should not be too hard to implement I think, even for composite-id PK, and may help many people by solving a point that is in the FAQ, meaning often asked.
I've done a custom version of this using an Interceptor, it's something like :
Code:
public class UnsavedInterceptor implements Interceptor {
private static final Logger logger = Logger.getLogger(UnsavedInterceptor.class);
Session currentSession = null;
public void setSession(Session session) {
currentSession = session;
}
/* (non-Javadoc)
* @see net.sf.hibernate.Interceptor#isUnsaved(java.lang.Object)
*/
public Boolean isUnsaved(Object entity) {
Boolean toReturn = Boolean.TRUE;
try {
if(entity instanceof Datasource) {
Object[] dsKey = {((Datasource)entity).getDatasourcePK().getIdDatasource(),((Datasource)entity).getDatasourcePK().getExhibit().getIdExhibit()};
Type[] dsKeyTypes = {new StringType(),new IntegerType()};
List results = currentSession.find("SELECT ds.DatasourcePK.idDatasource FROM Datasource as ds WHERE ds.DatasourcePK.idDatasource=? AND ds.DatasourcePK.exhibit.idExhibit=?",dsKey,dsKeyTypes);
if(results != null && !results.isEmpty()) {
toReturn = Boolean.FALSE;
}
} else if(entity instanceof [...]
} catch(Exception e) {
logger.error("isUnsaved(" + entity + "):" + e.toString());
logger.debug("isUnsaved(" + entity + "):", e);
}
return toReturn;
}
[...default implementation of other methods...]
}
First problem: is I have to pass the current session to the Interceptor BEFORE I call saveOrUpdate().
Second problem: the Interceptor is "global" (called for any entity type) so I have to manually re-implement the strategy even for entities with unsaved-value="null".
Third problem: I have to manually do the correct HQL for each type of entity to look for a record with the same PK as the entity passed in argument.
Hibernate version: 2.1.4 [/url]