John Hendrik
John Hendrik

Reputation: 661

JPA one-many gives null value after mapping

Could someone point out what I am doing wrong (followup on earlier question)?

I have three classes: Dashboard, DashboardUser and User.

Dashboard works fine, with the following code:

 @OneToMany(cascade= CascadeType.ALL, orphanRemoval = true, mappedBy="dashboard")
    private List<DashboardUser> dashboardUsers = new ArrayList<>();

DashboardUser contains the following two JPA declarations:

    @Id
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "IDUser")
    private User user;

    @Id
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "IDDashboard")
    private Dashboard dashboard;

The problem lies with User.java:

@OneToMany(cascade= CascadeType.ALL, orphanRemoval = true, mappedBy="user")
    private List<DashboardUser> dashboardUsers;

It looks the same, but only the Dashboard class works as it should. After executing my code, my dashboard has a dashboardUser among his attributes, the user however has a null value for dashboardUser.

The table in the database has two fields: IDUser and IDDashboard (I do use the right userID and dashboardID). Does someone see my mistake?

Upvotes: 1

Views: 1553

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94479

Add an @JoinColumn annotation to User

@OneToMany(cascade= CascadeType.ALL, orphanRemoval = true, mappedBy="user")
@JoinColumn(name="dashBoardUserId") //Replace with actual column name
private List<DashboardUser> dashboardUsers;

I had to guess the name of the primary key in DashboardUser so it will need replaced within the actual code.

After taking a further look at the code, I assumed that DashboardUser is a junction table between Dashboard and User which maps what dashboards a user has access. This scenario is best mapped by a @ManyToMany relationship. One user may have access to many dashboards, while a dashboard may have many users, hence a many to many relationship. The following mapping would create a many to many relationship between user and dashboard.

User.java

public class User{

    @ManyToMany(cascade={CascadeType.ALL}, targetEntity=Dashboard.class)
        @JoinTable(name="DASHBOARD_USER", 
        joinColumns={@JoinColumn(name="IDUser", referencedColumnName="IDUser")},
        inverseJoinColumns={@JoinColumn(name="IDDashboard",       
        referencedColumnName="IDDashboard")})
     public List<Dashboard> dashboards = new ArrayList<Dashboard>();

     //Other fields/Getters/Setters 
}

Dashboard.java

@Entity
public class Dashboard{

     @ManyToMany(mappedBy="dashboards")
     private List<Users> users;

     //Other fields/Getters/Setters

}

Upvotes: 2

Related Questions