2012-11-10 192 views
1

我有两个JPA实体:PersonAddressJPA cascade not working

Address类是不同类使用的常见类。

Person类我有一个@OneToOne关系,因为这:

@OneToOne(cascade = CascadeType.ALL) 
private Address address; 

我使用JPA与RESOURCE_LOCAL选项,在一个独立的应用程序。

我实例化一个Person,Address,填写所有属性并要求JPA保存全部为em.merge(person)

由于记录已经存在于数据库中,我希望JPA更新所有信息。但是,如果我也对人员实例进行了更改,它只会更新地址信息。如果我只是更改地址实例的某些信息并要求JPA保存Person,则不会更新任何内容。我通过Hibernate检查生成的SQL,并且在merge()操作中,它只执行SELECTperson表(加入address表)。

PersonAddress类中,我有equals()hashCode()以及Eclipse的默认实现。

关于如何级联更新到Address的任何想法?

+0

您能向我们展示rele vant代码,我的意思是创建并合并这些对象的代码? –

+0

Hi @ bhesh-gurung!代码基本实例化Person和Address,在Person实例上设置地址并调用em.merge(person)。但是它们中的两个已经存在于数据库中,所以我期待更新。 –

回答

0

在你Person类:

@OneToOne(cascade = CascadeType.ALL) 
private Address address; 

同时节约,你可以做到以下几点:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
Session session = sessionFactory.openSession(); 

session.beginTransaction(); 
session.saveOrUpdate(person); 

// Hibernate will automatically update because the object is in persistence context 
address.setStreetName(" Updated Street Name"); 

// Hibernate will automatically update because the object is in persistence context 
person.setPersonName("Updated Name"); 

session.getTransaction().commit(); 

// person object is now detached 
session.close(); 

现在,如果你尝试更新要么PersonAddress,他们不会因为更新该对象现在是分离的:

user.setUserName("If you try to update, it will not since session is closed"); 
address.setStreetName("If you try to update, it will not since session is closed");