我是 Hibernate 的新手,我正在处理这个令人沮丧的问题。我有两个班级:Location
和Address
。Address
是一个实体,具有Location
主键的外键。所以这里是Location
public class Location implements Serializable {
//Rest of code omitted
@OneToOne(mappedBy = "location", cascade = CascadeType.ALL)
public Address getAddress() {
return address;
}
}
和Address
public class Address implements Serializable {
//Rest of code ommitted
@OneToOne
@JoinColumn(name = "LOCATION_FK")
public Location getLocation() {
return location;
}
}
我正在尝试更新位置对象的地址,但我猜它没有发生。
public void updateAddress(Location location, Address address) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
tx.begin();
Location persistedLocation = (Location) session.get(Location.class, location.getId());
Address persistedAddress = persistedLocation.getAddress();
session.delete(persistedAddress);
persistedLocation.setAddress(address);
tx.commit();
session.close();
}
这是我的单元测试
//Setting variables
Location location = new Location();
Address address = new Address("123456", "TOWN", "CITY", 12345);
LocationDAO instance = new LocationDAO();
//Add the first location
boolean result = instance.addLocation(location, address);
assertTrue(result);
//Get it back from database
Location persistedLocation = instance.getLocations().get(0);
assertEquals(location.getAddress().getAddressLine(), persistedLocation.getAddress().getAddressLine());
Address newAddress = new Address("987654321", "Chicago", "IL", 11234);
instance.updateAddress(persistedLocation, newAddress);
persistedLocation = instance.getRentalLocations().get(0);
//Fails on the line below
//assertEquals(newAddress.getAddressLine(), persistedLocation.getAddress().getAddressLine());
我究竟做错了什么 ?谢谢