我有一个与权限类相关的用户类,它们之间具有manyToMany关系。
我正在使用投影来检索没有某些字段的用户列表。当我检索用户拥有的权限列表时出现问题,因为每个权限spring都会返回两次相同的对象。
用户类
@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;
}
用户存储库
@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();
}
}
正如您在输出中看到的那样,它返回相同用户的两倍但具有不同的角色。
输出
[
{
"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"
}
]
}
]
答案 0 :(得分:1)
这很可能就是这个Bug https://jira.spring.io/browse/DATAJPA-1173
它已在当前版本的Spring Data中修复,因此升级您使用的版本应解决问题。