JPA级联无效

时间:2015-10-06 21:10:56

标签: hibernate jpa hibernate-mapping jpa-2.1 hibernate-cascade

情景:

`
@Entity
@Table(name = "a")
@AttributeOverride(name = "id", column = @Column(name = "a_id"))
public class A {
   private ...
   private List<> ....
}`

`
@Entity
@Table(name = "b")
@AttributeOverride(name = "id", column = @Column(name = "b_id"))
public class B {
  @ManyToOne
  @JoinColumn(name = "a_id", referencedColumnName = "a_id")
  private A a;

  @Column(name = "last_opened_date")
  private DateTime lastOpenedDate;

  @ManyToOne(fetch = javax.persistence.FetchType.LAZY)
  @JoinColumn(name = "opened_by_id", referencedColumnName = "user_id")
  private User openedBy;
}`
  • 每当在视图中访问A时,A的状态都会发生变化。
  • A可以被许多用户访问。
  • 一旦访问A,就会为每个打开A的用户创建一个B实例(如果不存在)或更新。
  • B始终引用A的状态更改实例。
  • 由于我没有在B类的ManyToOne映射中提到过级联类型(对于A类),我假设默认情况下是cascade none。

但每当我在视图中打开A时,当B持续存在时,状态改变A也会持续存在。当我坚持B.我不希望A持久存在 我如何实现这一目标?

java 1.8,hibernate 4.3.7,wildfly 8.2

通用保存方法

public T save(T entity) throws PersistenceException {
    this.getEntityManager().joinTransaction();
    if (entity.getId() == null) {
        this.getEntityManager().persist(entity);
    } else {
        entity = this.getEntityManager().merge(entity);
    }
    return entity;
}

持久性xml

<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="bla_bla" transaction-type="JTA"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <jta-data-source>jdbc/bla</jta-data-source> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties> <property name="hibernate.enable_lazy_load_no_trans" value="true"/> <property name="hibernate.show_sql" value="false"/> <property name="hibernate.event.merge.entity_copy_observer" value="log"/> <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect"/> <property name="hibernate.transaction.jta.platform" value="org.hibernate.engine.transaction.jta.platform.internal.JBossAppServerJtaPlatform"/> <!-- enabling L2 cache --> <property name="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory"/> <property name="hibernate.generate_statistics" value ="false" /> <property name="hibernate.cache.use_second_level_cache" value="true"/> <property name="hibernate.cache.use_query_cache" value="false"/> <property name="jadira.usertype.databaseZone" value="UTC"/> <property name="jadira.usertype.javaZone" value="UTC"/> <property name="jadira.usertype.autoRegisterUserTypes" value="true"/> </properties> </persistence-unit> </persistence>

0 个答案:

没有答案