spring-boot-starter-data-jpa @ ManyToMany集合未填充

时间:2019-01-22 17:55:08

标签: java spring-boot jpa spring-boot-jpa

我遇到了@ManyToMany集合未在数据加载时填充的问题。我尝试了FetchType.LAZY和FetchType.EAGER,但结果没有变化。

当我打印用户对象时,角色的集合对象为空。

用户[userId = 2,firstName = Ajay,lastName = C,email = admin.demo @ gmail.com,密码= 12345,roles = []]

也尝试通过添加引用的列。但是没用。

请协助解决此问题。

用户和角色实体如下。

@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
}

1 个答案:

答案 0 :(得分:1)

您可以尝试-

@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;
}

我在这里添加了

  
      
  1. cascade = CascadeType.ALL
  2.   
  3. 目录=“ \” PLATFORM_PROD_IOT \“”而不是架构=“ \” PLATFORM_PROD_IOT \“”
  4.   
  5. nullable = false,可更新= false @JoinColumn
  6.   

还发现了一个相关的- collection not populating in many to many relationship