我正在使用hibernate和H2数据库开发Spring Boot应用程序。生成应用程序后,该应用程序将按预期创建表。在创建表之后,我手动将角色添加到角色表(role_id = 1, role = "USER"
)中,然后运行该应用程序。我可以成功添加第一个用户,其角色是USER,但是当我尝试添加第二个记录时,出现错误。另外,我可以成功添加第一个角色为ADMIN的用户后,添加另一个角色(role_id = 2, role="ADMIN"
)。但是第二个不能。为什么我不能添加多个记录?
错误是
*无法执行语句; SQL [n / a];约束[\“ UK_IT77EQ964JHFQTU54081EBTIO_INDEX_B在PUBLIC.USER_ROLE(ROLE_ID)上 VALUES(2,1)\“; SQL语句:\ n插入user_role(user_id, role_id)值(?,?)[23505-197]];嵌套异常为 org.hibernate.exception.ConstraintViolationException:无法 执行语句。
这是我的代码块。
User.java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private Long id;
private String name;
@Column(unique = true)
private String username;
@JsonProperty(access = Access.WRITE_ONLY)
private String password;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private List<Role> roles = new ArrayList<>();
}
Role.java
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private int roleId;
@Column(name = "role")
private String role;
public Role() {
}
public Role(String role) {
this.role = role;
}
}
注册方法
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<User> createUser(@RequestBody User user){
if(userRepository.findByUsername(user.getUsername()) != null) {
throw new RuntimeException("Username already exist");
}
List<Role> roles = new ArrayList<>();
roles.add(roleRepository.findByRole("USER"));
user.setRoles(roles);
return new ResponseEntity<User>(userRepository.save(user), HttpStatus.CREATED);
}
数据库表
CREATE CACHED TABLE PUBLIC.USER_ROLE(
USER_ID INTEGER NOT NULL,
ROLE_ID INTEGER NOT NULL
);
CREATE CACHED TABLE PUBLIC.USER(
USER_ID INTEGER DEFAULT (NEXT VALUE FOR
PUBLIC.SYSTEM_SEQUENCE_2149846F_F3B8_4E83_9B93_C1C67BF9DEA9) NOT NULL
NULL_TO_DEFAULT SEQUENCE
PUBLIC.SYSTEM_SEQUENCE_2149846F_F3B8_4E83_9B93_C1C67BF9DEA9,
NAME VARCHAR(255),
PASSWORD VARCHAR(255),
USERNAME VARCHAR(255)
);
CREATE CACHED TABLE PUBLIC.ROLE(
ROLE_ID INTEGER DEFAULT (NEXT VALUE FOR
PUBLIC.SYSTEM_SEQUENCE_44142DBD_5E4A_4D30_AB39_36956E6C6DAF) NOT NULL
NULL_TO_DEFAULT SEQUENCE
PUBLIC.SYSTEM_SEQUENCE_44142DBD_5E4A_4D30_AB39_36956E6C6DAF,
ROLE VARCHAR(255)
);