2011-08-03 32 views
0

我有兩個簡單的對象;人和城市。一個城市可能有多個人,但只有一個人只有一個城市。我希望能夠保存一個人並讓Hibernate自動保存城市 - 只有當它是一個新城市時 - 也就是說城市應該是獨一無二的。通過我的映射,我發現每次保存一個人時,都會在數據庫中插入一個新城市,無論它是否已經存在。我相信這是相當直接的,但我是Hibernate的新手,併爲此付出了努力。請注意,如果我在一個會話中將兩個人保存爲一個城市 - 所有作品。這是跨會話的問題。我還在City類中創建了equals和hashcode方法,如下所示。如何防止休眠在多對一的映射中創建重複

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; 

回答

1
if (!(other instanceof Ward)) return false; 
    final Ward that = (Ward) other; 

不應該是這個城市,而不是結界?

+0

謝謝 - 已經做出了更正...... – skyman

+0

儘管代碼仍然存在問題... – skyman

+0

您如何在其他對象中設置City屬性?你如何創建城市對象? – dfb