2012-02-11 11 views
2

でNonUniqueObjectExceptionを防ぐため、私は次の例外を取得:私は重複を望んでいないであろうからが休止状態

NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [org.wah.model.ImageEntity#7] 

これは、良いです。私は、コード内でこれを防ぐために試してみてください。

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(); 
} 

他-場合構築物は、それが既に存在するかどうかを確認しようとし、それについて何もしないで、そのまま返します。ただし、else-if条件はTRUEに評価されず、セッションコードが実行され、NonUniqueObjectExceptionが生成されます。

これを防ぐにはどうすればよいですか?

答えて

3

あなたはdestination.getImages().contains(image)trueに評価されたことがないと2 ImageEntitiesが同じ都市を持っている場合、あなたがオーバーライドする必要がありますする必要があることを意味する場合ImageEntityさんequals -method:

@Override 
public boolean equals(Object o) { 
    if (this == o) return true; 
    if (o == null || getClass() != o.getClass()) return false; 

    ImageEntity that = (ImageEntity) o; 

    if (city != null ? !city.equals(that.city) : that.city != null) return false; 

    return true; 
} 
+0

ありがとう!私はまた、なぜそれがそうでなければオブジェクトの参照チェックをしていたので失敗したのか理解しています。私たちは価値のある小切手を求めました。また、equalsとhashCodeを実装した後、私はgoogleグアバとapacheの共通言語を介してcamを使用します。今使っているものを学ぶ。 – brainydexter