'JPA @ManyToMany association not fetching owner class' collection
I have a simple Many-to-Many relationship between a User and Role entity. The tables are correctly created. Every time I add a role to a user, the USER_ROLE table is correctly updated with the user_id and role_id. But when fetching all the users, the roles collection is always empty.
User.java
@Entity
@Table(name = "USER")
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class User extends BaseEntity {
@Column(
name = "USERNAME",
unique = true,
nullable = false
)
private String username;
@Column(
name = "PASSWORD",
nullable = false
)
private String password;
@Column(name = "DEPOSIT")
private int deposit;
@ManyToMany(
fetch = FetchType.EAGER,
cascade = CascadeType.PERSIST
)
@JoinTable(
name = "USER_ROLE",
joinColumns = @JoinColumn(name = "USER_ID"),
inverseJoinColumns = @JoinColumn(name = "ROLE_ID")
)
private Collection<Role> roles = new HashSet<>();
}
Roles.java
@Entity
@Table(name = "ROLE")
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class Role extends BaseEntity {
@Column(
name = "NAME",
nullable = false,
unique = true
)
private String name;
@ManyToMany(mappedBy = "roles")
@JsonIgnore
private Collection<User> users = new HashSet<>();
}
BaseEntity.java
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
@Id
@GeneratedValue(
generator = "UUID"
)
@GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
@Column(
name = "ID",
updatable = false
)
private UUID id;
}
I saw this question many times on stackoverflow. I've tried multiple solutions but none of them worked and i can't seem to find the issue.
Edit: I have no ideas why, but it seems that the issue was coming from the fact that I was using UUID as primary keys. Now that I changed it to long values, it's working properly.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
