※狀況概述:
我嘗試在Hibernate,以純物件的方式來做crud,例如以下的code:
※程式碼:
coutry:
public class Country {
int countryId;
String countryName;
String countyCreateDate;
......
}
country的映射檔:
<hibernate-mapping package="com.test.vo">
<class name="Country" table="COUNTRY">
<id name="countryId" column="COUNTRY_ID">
<generator class="sequence">
<param name="sequence">country_id_seq</param>
</generator>
</id>
<property name="countryName" column="COUNTRY_NAME" />
<property name="countyCreateDate" column="COUNTRY_CREATE_DATE" />
</class>
</hibernate-mapping>
customer:
@Entity
@Table(name="CUSTOMER")
public class Customer {
@Id
@Column(name="CUSTOMER_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator =
"seq_customer_id")
@SequenceGenerator(name="seq_customer_id",
sequenceName="seq_customer_id",allocationSize=1)
int customerId;
@Column(name="NAME")
String name;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="COUNTRY_ID", referencedColumnName = "COUNTRY_ID")
Country country;
......
}
在DAO進行修改資料的動作:
public void edit(Customer customer,String address){
Session session2 = getHibernateTemplate().getSessionFactory().openSession();
Transaction tx2 = session2.beginTransaction();
Country country = new Country();
country.setCountryName(address);
customer.setCountry(country);
session2.update(customer);
tx2.commit();
}
※錯誤訊息:
沒有跳錯誤訊息,但是每次做修改的時候,都會額外新增一筆country的資料出來。
例如修改customer為Billy的country為Taipei,例如:
https://i.imgur.com/2C6uTwP.png
除了Billy的country會被修改為Taipei外,
country的表格也會額外新增一筆Taipei的資料出來,若我重複修改,那Taipei的資料
也會重複一直新增,就變成以下這樣:
https://i.imgur.com/Nc1G4BA.png
可以看到Taipei的資料重複出現。
請問是哪裡沒有配置好,才導致這樣呢?那應該如何修改,才能避免每次修改customer
都額外新增country資料呢?
※補充說明: