gpt4 book ai didi

java - 如何在 hibernate 中正确设置双向关联@OneToMany

转载 作者:行者123 更新时间:2023-12-02 09:09:11 25 4
gpt4 key购买 nike

我想创建双向@OneToMany 连接,但我认为我误解了一些东西。我有用户实体:

public class User {

@Id
@GeneratedValue(strategy = AUTO)
private Long id;
private String name;
private String password;

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Team team;
}

和团队实体:

public class Team {

@Id
@GeneratedValue(strategy= AUTO)
private Long id;

private String name;

@OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.EAGER,
mappedBy = "team")
private Set<User> users = new HashSet<>();
}

用户只能拥有一个团队,但团队可以拥有多个用户。我尝试测试一下:

 User user = new User();
Team team = new Team();
team.setName("test_team");
user.setTeam(team);
userRepository.save(user);

userRepository.findAll() 返回我:

[{"id":1,"name":null,"password":null,"team":{"id":2,"name":"test_team","users":[]}]

teamRepository.findAll() 返回我:

[{"id":2,"name":"test_team","users":[]}]

为什么会发生这种情况?我想创建双向连接,但团队实体似乎不了解任何用户。

如何创建一个连接,如果我添加用户实体或更新用户的团队,团队实体也会更新?

最佳答案

您在父端缺少 @JoinColumn:

@JoinColumn(name = "team_id")
@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Team team;

关于java - 如何在 hibernate 中正确设置双向关联@OneToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59542897/

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