0

我是 Hibernate 的新手,我正在处理这个令人沮丧的问题。我有两个班级:LocationAddressAddress是一个实体,具有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()); 

我究竟做错了什么 ?谢谢

4

1 回答 1

1

该关联是 "mappedBy" Address.location。这意味着 Hibernate 只考虑关联的这一面(所有者方),而忽略另一方(反面)。

但是您的代码只初始化了反面,而忽略了初始化所有者的一面。因此,该关联不会保留在数据库中。

你的 DAO 中需要这一行:

address.setLocation(persistedLocation);
于 2013-06-08T20:51:34.360 回答