I'm getting a problem with the @ManyToMany collections not populating on data load. I've tried FetchType.LAZY and FetchType.EAGER with no changes in the result.
When I am printing the User Object the collection Object of Roles is empty.
User [userId=2, firstName=Ajay, lastName=C, [email protected], password=12345, roles=[]]
Also tried by adding referenced columns. But not worked.
Please assist in this.
User and Roles Entities as follows.
@Entity
@Table(name = "\"USER\"", schema = "\"PLATFORM_PROD_IOT\"", uniqueConstraints = {
@UniqueConstraint(columnNames = { "\"EMAIL_ID\"" }) })
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Size(min = 1, max = 50)
@Column(name = "\"USER_ID\"")
private Long userId;
@NotBlank
@Size(min = 3, max = 50)
@Column(name = "\"FIRST_NAME\"")
private String firstName;
@NotBlank
@Size(min = 3, max = 50)
@Column(name = "\"LAST_NAME\"")
private String lastName;
@NaturalId
@NotBlank
@Size(max = 50)
@Email
@Column(name = "\"EMAIL_ID\"")
private String email;
@NotBlank
@Size(min = 3, max = 100)
@Column(name = "\"PASSWORD\"")
private String password;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "\"USER_ROLE_MAPPING\"", schema = "\"\PLATFORM_PROD_IOT\"", joinColumns = @JoinColumn(name = "\"USER_ID\""), inverseJoinColumns = @JoinColumn(name = "\"ROLE_ID\""))
private Set<Role> roles = new HashSet<>();
//Getters and Setters
}
@Entity
@Table(name = "\"ROLE\"",schema="\"PLATFORM_PROD_IOT\"")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="\"ROLE_ID\"")
private Long roleId;
@Column(name="\"ROLE_NAME\"")
private RoleName name;
//Getters and Setters
}
You could try this -
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "\"USER_ROLE_MAPPING\"", catalog = "\"PLATFORM_PROD_IOT\"", joinColumns = {
@JoinColumn(name = "\"USER_ID\"", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "\"ROLE_ID\"",
nullable = false, updatable = false) })
private Set<Role> roles = new HashSet<>();
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
Here I have added
- cascade = CascadeType.ALL
- catalog = "\"PLATFORM_PROD_IOT\"" instead of schema = "\"PLATFORM_PROD_IOT\""
- nullable = false, updatable = false in @JoinColumn
Also have found an related - collection not populating in many to many relationship