java - Hibernate,@ManyToOne/@OneToMany,添加的子项未与父项一起获取

标签 java hibernate

我或多或少有类似 hibernate 和 h2/postgres 的设置(两者都无法正常工作)

@Entity
class A {

    @Id
    @GeneratedValue
    long id;

    @OneToMany(mappedBy = "a", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    List<B> bs;

}

@Entity
class B {

    @Id
    @GeneratedValue
    long id;

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) 
    A a;
}

现在,有带有 save/update/getAll/getById 方法的 @Transactional 存储库。

我的问题是当我执行以下操作时:

A a = new A();
save(a);

B b = new B();
b.a = a;
save(b);

A anotherA = getById(a.id);

名为“anotherA”的对象在“bs”字段中没有任何 B 对象。

我应该做些什么来实现它还是我的方法有问题?

此外,当我在一段时间后调用最后一行时,bs被填满,所以我怀疑 session 和存储在那里的A对象可能有问题。

最佳答案

您必须确保在关系的两侧应用该关系,如下所示:

A a = new A();
session.save( a );

B b = new B();
b.setA( a );
a.getBList().add( b );
session.save( b );

通常,为了避免将此类代码放在应用程序的各个位置,我通常会公开一个为我管理此关系的参与者方法。

// a method inside B
public void applyA(A a) {
  // if B is currently related to A, break the relation
  if ( this.a != null ) {
    this.a.getBList().remove( this );
  }
  // apply the relation to both sides
  this.a = a;
  if ( a != null ) {
    a.getBList().add( this );
  }
}

同样,您可以向 A 添加类似的方法

public void applyB(B b) {
  if ( b != null && !this.bList.contains( b ) ) {
    b.apply( this );
  }
}

关于java - Hibernate,@ManyToOne/@OneToMany,添加的子项未与父项一起获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38792759/

相关文章:

java - 比较存储在 hashmap 中的值的对象

java - 我的图形无法绘制

java - 非常奇怪的鼠标监听器和 If 语句

mysql - JPA/hibernate : Missing table error

java - 插入性能: Use HashSet at begin vs use ArrayList at begin and use hashset to remove duplicate at the end

java - Spring Data JPA 表连接创建运算符不存在错误

java - Hibernate 在充当主键的另一个实体上进行一对一映射

java - 使用 hibernate 注释将枚举映射到表

hibernate - ManyToMany关联删除连接表条目

java - hibernate 错误: Illegal Attempt to deference collection