我遇到了一个问题,我需要一个可以在多个公司中注册的用户。这些公司可以注册多个产品。用户应该知道他拥有哪些公司的产品。
到目前为止,这是我的解决方案,但是无法正确返回角色:
class User {
@Id
@Column(name = "USER_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "USERNAME", unique = true)
private String username;
@Column(name = "PASSWORD")
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "USER_ROLES",
joinColumns = {@JoinColumn(name = "USER_ID"), @JoinColumn(name = "COMPANY_ID"), @JoinColumn(name="PRODUCT_ID")},
inverseJoinColumns = {@JoinColumn(name = "ROLE_ID"), @JoinColumn(name = "COMPANY_ID"), @JoinColumn(name="PRODUCT_ID")})
private Set<Role> roles = new HashSet<>();
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "USER_COMPANIES",
joinColumns = {@JoinColumn(name = "USER_ID")},
inverseJoinColumns = {@JoinColumn(name = "COMPANY_ID")})
private Set<Company> companies = new HashSet<>();
}
class Role {
@Id
@Column(name = "ROLE_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "ROLE_NAME")
@Enumerated(EnumType.STRING)
@NaturalId
private RoleName role;
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
@JsonIgnore
private Set<User> userList = new HashSet<>();
}
class Company {
@Id
@Column(name = "COMPANY_ID")
private Long id;
@ManyToMany(mappedBy = "companies", fetch = FetchType.LAZY)
@JsonIgnore
private Set<User> userList = new HashSet<>();
@OneToMany(mappedBy = "company")
private Set<Product> products;
}
class Product {
@Id
@Column(name = "COMPANY_ID")
private Long id;
@ManyToOne
@JoinColumn(name="COMPANY_ID", nullable=false)
private Company company;
private ProductType productType;
}
我的最终目标是从用户那里获得角色,任何人都可以帮忙吗? 提前非常感谢!
答案 0 :(得分:0)
@ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "USER_ROLES", joinColumns = {@JoinColumn(name = "USER_ID"),
@JoinColumn(name = "COMPANY_ID"), @JoinColumn(name="PRODUCT_ID")}, inverseJoinColumns =
{@JoinColumn(name = "ROLE_ID"), @JoinColumn(name = "COMPANY_ID"),
@JoinColumn(name="PRODUCT_ID")})
***@JsonBackReference***
private Set<Role> roles = new HashSet<>();
尝试使用pojo用户中的@ JsonBackReference。@ JsonBackReference将在反序列化过程中为用户设置角色。