簡體   English   中英

如何在休眠中正確設置雙向關聯@OneToMany

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

我想創建一個雙向的@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;

請考慮以下幾點並進行相應更改:

  1. 將實體中的 id 更改為 userId 和 teamId 以使其區分,
  2. 在用戶實體中的團隊屬性上方添加 @JoinColumn(name = "teamId")。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM