我正在尝试通过此 json 多对多更新我的实体: 正如你所看到的,我有这样的关系:Utente-Ruoli,Ruoli-Privileggi
{
"user": {
"id": 1,
"username": "ttt",
"dataCreazione": "2023-09-21T08:00:00.000+0000",
"dataUltimoAccesso": "2023-09-21T09:30:00.000+0000"
},
"roles": [
{
"id": 2,
"roleName": "ADMIN",
"description": "admin",
"privileggi": [
{
"id": 1,
"privName": "tt",
"description": "basic user",
"active": false
},
{
"id": 3,
"privName": "ee",
"description": "admin role",
"active": true
},
{
"id": 4,
"privName": "ss",
"description": "archicon role",
"active": true
}
]
}
]
}
这是我的Utente JPA中的方法:
@Modifying(flushAutomatically = true, clearAutomatically = true)
@Transactional
@Query("UPDATE Utente u SET u.roles = :roles WHERE u.id = :userId")
int saveUserRoles(@Param("userId") Integer userId, @Param("roles") Set<Ruoli> roles);
这就是我提供服务的地方:
public Utente addRolesToUser(RuoliDTO ruoliDTO) {
log.info("{}.addRolesToUser adding user: {} to list roles: {}", this.getClass().getName(), ruoliDTO.getUser().getUsername(), ruoliDTO.getRoles().size());
Utente utente = ruoliDTO.getUser();
Set<Ruoli> rolesToAdd = ruoliDTO.getRoles();
utente.setRoles(ruoliDTO.getRoles());
userRepository.saveUserRoles(utente.getId(), rolesToAdd);
return utente;
}
我总是遇到这个错误:
Parameter value [Ruoli{id=2, roleName='ADMIN', description='admin', privileggi=[Privileggi{id=1, privName='UNICACON_MDJS_USER', description='basic user', active=false}, Privileggi{id=3, privName='UNICACON_MDJS_ADMIN', description='admin role', active=true}, Privileggi{id=4, privName='ARCHICON_MDJS_USER', description='archicon role', active=true}]}] did not match expected type [java.util.Set (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [Ruoli{id=2, roleName='ADMIN', description='admin', privileggi=[Privileggi{id=1, privName='UNICACON_MDJS_USER', description='basic user', active=false}, Privileggi{id=3, privName='UNICACON_MDJS_ADMIN', description='admin role', active=true}, Privileggi{id=4, privName='ARCHICON_MDJS_USER', description='archicon role', active=true}]}] did not match expected type [java.util.Set (n/a)]
我做错了什么?
我不确定
UPDATE
是否是正确的操作,因为像这样更新多对多表并不常见。由于您要添加角色,因此应该是一个 INSERT
操作,如果您只想替换全部,请先执行 DELETE
。
如果您想进行批量
INSERT
来提高性能,请查看 saveAll
方法:https://stackoverflow.com/a/50882952/20991328
以下是答案
首先,您需要从数据库中获取Utente实体。
然后,您可以使用 RuoliDTO 中的角色更新 Utente 实体的角色。
最后,您可以将更新后的Utente实体保存回数据库。
public Utente addRolesToUser(RuoliDTO ruoliDTO) {
log.info("{}.addRolesToUser adding user: {} to list roles: {}", this.getClass().getName(), ruoliDTO.getUser().getUsername(), ruoliDTO.getRoles().size());
// 1. Fetch the Utente entity from the database.
Utente utente = userRepository.findById(ruoliDTO.getUser().getId()).orElse(null);
if (utente != null) {
// 2. Update the Utente entity's roles with the roles from RuoliDTO.
utente.setRoles(ruoliDTO.getRoles());
// 3. Save the updated Utente entity back to the database.
utente = userRepository.save(utente);
}
return utente;
}