我正在尝试创建注册过程,这是我的代码:
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嵌入式数据库,因此仅用于培训)。请帮忙。
答案 0 :(得分:0)
您是否将数据库配置为自动生成id字段?如果不是,那么每个对象中id的默认值将为0(long的默认值)。
答案 1 :(得分:0)
将子句 AUTO_INCREMENT 添加到表用户的列 id 的定义中。
实体中的注释 @GeneratedValue(strategy = GenerationType.AUTO)用户意味着在将对象用户插入数据库时,数据库将自动生成id字段的值。