0

设想:

`
@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 类(对于 A 类)的 ManyToOne 映射中提到级联类型,我假设默认值为无级联。

但是每当我在视图中打开 A 时,当 B 持续存在时,状态更改的 A 也会持续存在。当我坚持 B 时,我不希望 A 坚持下去。我该如何实现?

java 1.8、休眠 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>

4

0 回答 0