1

我正在插入一个带有角色(现有)角色的用户对象。它让我无法在 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);
}
4

1 回答 1

1

您的user_role连接表有一个idHibernate 不知道的列。hibernate 只知道role_iduser_id列。该id列没有用,您应该将其从user_role表中删除。如果你把它留在那里,你需要让它可以为空,或者让它有一个默认值。

于 2013-01-25T09:19:08.607 回答