Adrian
Adrian

Reputation: 502

How to properly set bidirectional association @OneToMany in hibernate

I want to create a bidirectional @OneToMany connection, but I think that I misunderstand something. 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:

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

teamRepository.findAll() returns me:

[{"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?

Upvotes: 0

Views: 54

Answers (2)

nirvidh patel
nirvidh patel

Reputation: 59

Please consider few point and make changes accordingly:

  1. Change id in both entity to userId and teamId to make it distinguish,
  2. Add @JoinColumn(name = "teamId") above team attribute in User entity.

Upvotes: 0

Andronicus
Andronicus

Reputation: 26046

You're missing @JoinColumn on the parent side:

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

Upvotes: 1

Related Questions