简体   繁体   中英

org.hibernate.exception.ConstraintViolationException when registering user

I am trying to create registration process, this is my code:

public class UserRegistrationDto {

private String firstName;
private String lastName;
private String password;
private String confirmPassword;
private String email;
private String confirmEmail;
private Boolean terms;
}

Role class:

@Entity
public class Role {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;

User class:

@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:

@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());
}
}

And i got this error:

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]

I have no idea, where I made a mistake, i tried to debug this, but didn't find an error. (I use H2 embedded datebase, cause its just for training). Please help.

Did you configure the database to auto-generate the id field? If not then the default value for the id in every object will be 0(default value for long).

Add clause AUTO_INCREMENT to definition of column id of table user .

Annotation @GeneratedValue(strategy = GenerationType.AUTO) in entity User means that database will be automatically generate values of id field upon insert objects User to database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM