更新OneToOne后出现NullPointerException

时间:2013-06-08 20:05:25

标签: hibernate

我是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()); 

我做错了什么?谢谢

1 个答案:

答案 0 :(得分:1)

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

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

你的DAO中需要这一行:

address.setLocation(persistedLocation);