title: How to join table with multiple columns - spring jpa @manytomany three join columns java
body: <p>I've come to a problem, where i have to a user which can be registered in multiple companies. Those companies can have registered multiple products. And user should be aware to which products in which companies he has rights. </p>
  
  <p>This is my solution so far, but it does not return the roles correctly:</p>
  
  <pre class="lang-java prettyprint-override"><code>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&lt;Role&gt; roles = new HashSet&lt;&gt;();
  
    @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&lt;Company&gt; companies = new HashSet&lt;&gt;();
  }
  
  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&lt;User&gt; userList = new HashSet&lt;&gt;();
  }
  
  class Company {
    @Id
    @Column(name = "COMPANY_ID")
    private Long id;
  
    @ManyToMany(mappedBy = "companies", fetch = FetchType.LAZY)
    @JsonIgnore
    private Set&lt;User&gt; userList = new HashSet&lt;&gt;();
  
    @OneToMany(mappedBy = "company")
    private Set&lt;Product&gt; products;
  }
  
  class Product {
    @Id
    @Column(name = "COMPANY_ID")
    private Long id;
  
    @ManyToOne
    @JoinColumn(name="COMPANY_ID", nullable=false)
    private Company company;
  
    private ProductType productType;
  
  }
  </code></pre>
  
  <p>My ultimate goal is to get roles from user, could anyone help, please?
  Thanks a lot in advance!</p>