0
두 개의 간단한 객체가 있습니다. 사람과 도시. 한 도시에는 여러 명의 인물이 있지만 한 인물에는 한 개의 도시 만있을 수 있습니다. 필자는 Person을 저장하고 Hibernate가 새로운 도시인 경우에만 도시를 자동 저장하도록하고 싶습니다. 즉, 도시는 고유해야합니다. 필자의 매핑을 통해 Person이 저장 될 때마다 새로운 City가 이미 존재하는지 여부에 관계없이 데이터베이스에 새로운 City가 삽입된다는 것을 알게되었습니다. 나는 이것이 매우 솔직하다고 확신하지만, 나는 Hibernate에 익숙하지 않으며 그것에 고심하고있다. 참고, 한 도시에 두 사람을 한 세션에 저장하면 모든 것이 작동합니다. 이는 여러 세션에서 발생하는 문제입니다. 또한 City 클래스에서 equals 및 hashcode 메소드를 아래와 같이 만들었습니다.Hibernate가 다 대일 매핑에서 중복을 생성하지 못하게하는 방법
Person.hbm.xml
<id name="id" type="long" column="id" >
<generator class="native"/>
</id>
<property name="firstName">
<column name="firstname" />
</property>
<many-to-one name="city" class="com.project.City" cascade="save-update">
<column name="cityId" not-null="true" />
</many-to-one>
City.hbm.xml
<id name="id" type="long" column="id" >
<generator class="native"/>
</id>
<property name="description" unique="true">
<column name="description" />
</property>
public class City implements java.io.Serializable {
private Long id;
private String description;
// getters and setters
public boolean equals(Object other) {
if (this==other) return true;
if (!(other instanceof City)) return false;
final City that = (City) other;
return this.description.equals(that.getDescription());
}
public int hashCode() {
return description.hashCode();
}
}
try {
Transaction tx = session.beginTransaction();
Criteria criteria = session.createCriteria(City.class);
criteria.add(Restrictions.eq("description", city.getDescription()));
criteria.setMaxResults(1);
// Possible to use:
// List<City> cities = criteria.list();
// However, this generates warnings about unsafe casting. If you use this then
// set @SuppressWarnings("unchecked")
List<City> cities = HibernateUtil.castList(City.class, criteria.list());
if (cities.isEmpty()) {
session.save(city);
}
else {
city = (City) cities.get(0);
}
session.flush();
tx.commit();
}
catch (Exception e) {
return null;
}
}
return city;
감사합니다. 수정했습니다 .... – skyman
코드에 여전히 문제가 있습니다 ... – skyman
다른 개체에 City 속성을 어떻게 설정하고 있습니까? City 객체는 어떻게 작성하고 있습니까? – dfb