简体   繁体   English

如何在休眠中正确设置双向关联@OneToMany

[英]How to properly set bidirectional association @OneToMany in hibernate

I want to create a bidirectional @OneToMany connection, but I think that I misunderstand something.我想创建一个双向的@OneToMany 连接,但我认为我误解了一些东西。 I have user entity:我有用户实体:

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;
}

and Team entity:和团队实体:

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 can have only one team, but team can have multiple users.用户只能有一个团队,但团队可以有多个用户。 I tried to test this:我试图测试这个:

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

userRepository.findAll() returns me: userRepository.findAll()返回我:

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

teamRepository.findAll() returns me: teamRepository.findAll()返回给我:

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

Why does this happen?为什么会发生这种情况? I want to create a bidirectional connection, but it seems that team entity doesn't know about any users.我想创建一个双向连接,但似乎团队实体不知道任何用户。

How to create a connection that if I add user entity or update the user's team also team entity will be updated?如何创建一个连接,如果我添加用户实体或更新用户的团队,团队实体也会更新?

You're missing @JoinColumn on the parent side:您在父端缺少@JoinColumn

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

Please consider few point and make changes accordingly:请考虑以下几点并进行相应更改:

  1. Change id in both entity to userId and teamId to make it distinguish,将实体中的 id 更改为 userId 和 teamId 以使其区分,
  2. Add @JoinColumn(name = "teamId") above team attribute in User entity.在用户实体中的团队属性上方添加 @JoinColumn(name = "teamId")。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM