2012-02-11 3 views
2

에 NonUniqueObjectException을 방지, 나는 다음과 같은 예외를 얻을. 나는 코드가 발생하지 않도록하려고 :최대 절전

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로 평가 결코 두 ImageEntities이 같은 도시가 있다면, 당신은 무시해야한다는 것을 의미하는 경우 ImageEntityequals -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 구현의 여파로 나는 구글 구아바와 아파치 공통 언어에 걸쳐 캠을 사용한다. 어느 것을 지금 사용하는지 배우십시오. – brainydexter