我正在插入一个带有角色(现有)角色的用户对象。它让我无法在 user_role.id 中插入 null
架构:
@Entity
@Table(name = "user_data")
public class User extends Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/**
* user can have set of roles profiles
*/
@ManyToMany(cascade = {CascadeType.ALL} ,fetch=FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") }, inverseJoinColumns = { @JoinColumn(name = "role_id", referencedColumnName = "id") })
private Set<Role> roles;
}
@Entity @Table(name = "role")
public class Role extends Serializable {
private static final long serialVersionUID = -5954247513572163065L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
@ManyToMany
@JoinTable(name = "role_permission", joinColumns = { @JoinColumn(name = "role_id",
referencedColumnName = "id") },
inverseJoinColumns = { @JoinColumn(name = "permission_id",
referencedColumnName = "id") })
private Set<Permission> permissions;
[...]
}
现在,当我尝试创建用户时,它给了我例外
java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("USER_ROLE"."ID"
)
为了创建用户,我使用如下 spring 存储库代码:
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public User createUser(User user) throws BusinessException {
List<Error> errors = new ArrayList<Error>();
validateUserRoles(user ,errors);
if ( errors.size() > 0 )
{
throw new BusinessException(errors);
}
user.setUserIdentifier(user.getUserIdentifier().trim());
logger.info("Creating User with username: " + user.getUserIdentifier());
return this.userRepositotry.save(user);
}
private void validateUserRoles(User user ,List<Error> errors) {
Set<Role> roles = new HashSet<Role>();
if (user.getRoles() != null)
{
for(Role role : user.getRoles())
{
Role r = null;
if(role.getId() != null)
{
r = this.roleRepository.findOne(role.getId());
} else if( role.getName() != null )
{
r = this.roleRepository.findByName(role.getName());
}
if(r == null)
{
errors.add(new Error(ErrorCode.INVALID_ARGUMENTS,"Invalid user Role.",r));
} else
{
roles.add(r);
}
}
}
user.setRoles(roles);
}