Search code examples
spring-bootspring-boot-jpa

@ManyToMany collection not populating with spring-boot-starter-data-jpa


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=admin.demo@gmail.com, 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 = "\"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
}
@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
}

Solution

  • Try it in class Role.

      @ManyToMany(fetch = FetchType.EAGER)
        @JoinTable(name = "USER_ROLE_MAPPING",joinColumns = @JoinColumn(name = "ROLE_ID"), inverseJoinColumns = @JoinColumn(name = "USER_ID""))
        private Set<Role> roles = new HashSet<>();
    

    And in class User change fetchType to EAGER. If it not work try change table to different name. Example: Users, Roles. Something it not work because it same name in SQL DATABASE.