gpt4 book ai didi

java - spring jpa - 如何保持可传递的双向关系

转载 作者:行者123 更新时间:2023-11-30 08:52:28 25 4
gpt4 key购买 nike

我有三个具有 OneToMany 关系的类(A、B、C) A <>-- B <>-- C代码:

@Getter @Setter
@Entity
public class A {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "a")
private List<B> bList;

private String name;
}

@Getter @Setter
@Entity
public class B {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne(fetch = FetchType.EAGER)
private A a;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "b")
private List<C> cList;

private String name;
}

@Getter @Setter
@Entity
public class C {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String name;

@ManyToOne(fetch = FetchType.EAGER)
private B b;
}

我应该如何正确填充数据?当我尝试这样的事情时:

    A a = new A();
a.setName("A-1");
aRepository.save(a);

B b1 = new B();
b1.setName("B-1");
b1.setA(a);
bRepository.save(b1);

B b2 = new B();
b2.setName("B-2");
b2.setA(a);
bRepository.save(b2);

for (int i = 1; i <= 9; i++ ) {
C c = new C();
c.setName("C-"+i);
c.setB(b1);
cRepository.save(c);
}

我在数据库中得到正确填充的数据:

+----+------+
| ID | NAME |
+----+------+
| 1 | A-1 |
+----+------+

+----+------+------+
| ID | NAME | A_ID |
+----+------+------+
| 1 | B-1 | 1 |
+----+------+------+
| 2 | B-2 | 1 |
+----+------+------+

+----+------+------+
| ID | NAME | B_ID |
+----+------+------+
| 1 | C-1 | 1 |
+----+------+------+
| 2 | C-2 | 1 |
+----+------+------+
| 3 | C-3 | 1 |
+----+------+------+
| 4 | C-4 | 1 |
+----+------+------+
| 5 | C-5 | 1 |
+----+------+------+
| 6 | C-6 | 1 |
+----+------+------+
| 7 | C-7 | 1 |
+----+------+------+
| 8 | C-8 | 1 |
+----+------+------+
| 9 | C-9 | 1 |
+----+------+------+

但是当我尝试从存储库中获取数据时出现了错误:

这些测试没问题:

    assertThat(cRepository.findOne(1l)).isNotNull();
assertThat(cRepository.findOne(1l).getB()).isNotNull();
assertThat(cRepository.findAll()).hasSize(9);
assertThat(bRepository.findAll()).hasSize(2);
assertThat(bRepository.findOne(1l).getCList().size()).isEqualTo(9);

但是这个失败了:

    assertThat(aRepository.findOne(1l).getBList().size()).isEqualTo(2);

它返回 10 条记录。查询 SELECT * FROM B WHERE A_ID = 1返回 2 条记录,那么您能否阐明我做错了什么?

最佳答案

它奇怪的 hibernate 行为是由于使用 OUTER JOINS 的 EAGER 类型造成的。对于与 B 相关的每个 C 对象,您都会得到重复的 B 对象。我遇到了类似的问题,我找到的唯一解决方案是将 fetchType 更改为 LAZY 或将 List 更改为 Set。

在这里你有更好的解释:Hibernate Criteria returns children multiple times with FetchType.EAGERDuplicates in OneToMany annotated List

关于java - spring jpa - 如何保持可传递的双向关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30172100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com