When I am trying to add a given image to the same destination city twice, I get the following exception:
NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [org.wah.model.ImageEntity#7]
This is good, since I wouldn’t want duplicates. I try to prevent this from happening in code:
public void addImageToDestination(int idDestination, String imageFileName){
Destination destination = (Destination) getEntity(idDestination);
ImageEntityDAO imageDao = new ImageEntityDAO();
ImageEntity image = imageDao.getImage(imageFileName);
if(image == null)
image = new ImageEntity(imageFileName);
else if(destination.getImages().contains(image)){
return;
}
session.beginTransaction();
destination.getImages().add(image);
session.getTransaction().commit();
}
The else-if construct tries to identify if it already exists, then do nothing about it and return as is. However, the else-if condition never evaluates to TRUE and session code is run, yielding the NonUniqueObjectException.
How can I prevent this from happening ?
If you mean that
destination.getImages().contains(image)never evaluates totrueand should if two ImageEntities have the same city, you should overrideImageEntity‘sequals-method: