![](/img/trans.png)
[英]Display valid msg to user for org.hibernate.exception.ConstraintViolationException:
[英]org.hibernate.exception.ConstraintViolationException when registering user
我正在尝试创建注册过程,这是我的代码:
public class UserRegistrationDto {
private String firstName;
private String lastName;
private String password;
private String confirmPassword;
private String email;
private String confirmEmail;
private Boolean terms;
}
角色类别:
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
用户类别:
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String email;
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"))
private Collection<Role> roles;
}
服务:
@Service
public class UserServiceImpl implements UserService {
(...)
public User save(UserRegistrationDto registration){
User user = new User();
user.setFirstName(registration.getFirstName());
user.setLastName(registration.getLastName());
user.setEmail(registration.getEmail());
user.setPassword(passwordEncoder.encode(registration.getPassword()));
user.setRoles(Arrays.asList(new Role("ROLE_USER")));
return userRepository.save(user);
}
private Collection<? extends GrantedAuthority> mapRolesToAuthorities(Collection<Role> roles){
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
}
我得到了这个错误:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint ["PRIMARY KEY ON PUBLIC.USER(ID)"; SQL statement: insert into user (email, first_name, last_name, password, id) values (?, ?, ?, ?, ?) [23505-196]]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause org.h2.jdbc.JdbcSQLException: Naruszenie ograniczenia Klucza Głównego lub Indeksu Unikalnego: "PRIMARY KEY ON PUBLIC.USER(ID)" Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.USER(ID)"; SQL statement: insert into user (email, first_name, last_name, password, id) values (?, ?, ?, ?, ?) [23505-196]
我不知道,我在哪里弄错了,我试图调试它,但是没有发现错误。 (我使用H2嵌入式数据库,仅用于培训)。 请帮忙。
您是否将数据库配置为自动生成id字段? 如果不是,则每个对象中id的默认值将为0(长时的默认值)。
将子句AUTO_INCREMENT添加到表user的列ID的定义中。
实体用户中的注释@GeneratedValue(strategy = GenerationType.AUTO)表示在将用户插入到用户数据库时,数据库将自动生成id字段的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.