I have a user class related to a authority class with a manyToMany relationship between them.
I am using a projection to retrieve a list of users without some fields. There is a problem when I retrieve the list of authorities the user has, for each authority spring returns me the same object twice.
User class
@Entity
@Table(name = "user")
public class User {
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "user_seq")
@SequenceGenerator(name = "user_seq", sequenceName = "user_seq", allocationSize = 1)
private Long id;
@Column(name = "apiKey", updatable = false, nullable = false, unique=true, columnDefinition = "BINARY(16)")
private UUID apiKey;
@Column(name = "USERNAME", length = 50, unique = true)
@NotNull
@Size(min = 4, max = 50)
private String username;
@Column(name = "PASSWORD", length = 100)
@NotNull
@Size(min = 4, max = 100)
private String password;
@Column(name = "FIRSTNAME", length = 50)
@NotNull
@Size(min = 4, max = 50)
private String firstname;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "USER_AUTHORITY",
joinColumns = {@JoinColumn(name = "USER_ID", referencedColumnName = "ID")},
inverseJoinColumns = {@JoinColumn(name = "AUTHORITY_ID", referencedColumnName = "ID")})
private List<Authority> authorities;
}
User repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByUsername(String username);
List<UserWithUuid> findAllByNodeId(Long nodeId);
interface UserWithUuid {
String getFirstname();
String getLastname();
String getEmail();
List<Authority> getAuthorities();
UUID getApiKey();
}
}
As you can see in the output it returns twice the same user but with a different role.
Output
[
{
"firstname": "daniel",
"lastname": "mancera",
"email": "daniel.mancera@dmance.eu",
"apiKey": "7961609f-79d4-4ef2-9baa-6809978c038b",
"authorities": [
{
"id": 1,
"name": "ROLE_USER"
}
]
},
{
"firstname": "daniel",
"lastname": "mancera",
"email": "daniel.mancera@dmance.eu",
"apiKey": "7961609f-79d4-4ef2-9baa-6809978c038b",
"authorities": [
{
"id": 2,
"name": "ROLE_MANAGER"
}
]
},
{
"firstname": "Roger",
"lastname": "Rabbit",
"email": "roger.rabiit@rab.it",
"apiKey": "023bf60b-e79b-461f-bd30-65a920fe99e4",
"authorities": [
{
"id": 1,
"name": "ROLE_USER"
}
]
}
]