我正在插入具有角色(现有)角色的User对象。 它让我无法在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);
}
答案 0 :(得分:0)
您的user_role
联接表有id
列,Hibernate不知道。所有hibernate都知道role_id
和user_id
列。 id
列无用,您应该从user_role
表中删除它。如果你把它留在那里,你需要让它可以为空,或者使它具有默认值。