web-dev-qa-db-fra.com

AutoIncrement Id PostgreSQL et Spring Boot Data JPA

J'ai des problèmes pour essayer de créer un nouvel enregistrement dans ma base de données PostgreSQL. Je veux juste POST to the REST service a new user (int: id, String: email, String: password) but, I'm having this Erreur:

"exception": "org.springframework.dao.DataIntegrityViolationException",
"message": "could not execute statement; SQL [n/a]; constraint [id]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

Ce sont mes Java classes:

Domaine

@Entity
@Table(name = "users")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;
  private String email;
  private String password;

  public User() {}

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
}

Manette

@RestController
@RequestMapping("/users")
public class UserController {
  @Autowired
  private UserService userService;

  @RequestMapping(method = RequestMethod.GET)
  public List<User> findAll() {
    return userService.findAll();
  }

  @RequestMapping(method = RequestMethod.POST)
  public User addUser(@RequestBody User user) {
    userService.addUser(user);
    return user;
  }
}

Un service

@Service
public class UserService {
  @Autowired
  private UserRepository userRepository;

  public List<User> findAll() {
    return (List<User>) userRepository.findAll();
  }

  public User addUser(User user) {
    userRepository.save(user);
    return user;
  }
}

Dépôt

public interface UserRepository extends CrudRepository<User, Integer> {
  // TODO
}

SQL

CREATE TABLE users(
    id INT PRIMARY KEY NOT NULL,
    email   TEXT NOT NULL,
    password    CHAR(20)    NOT NULL
);

S'il vous plaît, quelqu'un m'aide, car je ne sais pas comment résoudre ce problème.

11
lbpeppers

J'ai trouvé la solution. J'ai besoin de changer le script pour celui-ci:

CREATE TABLE users(
    id  SERIAL PRIMARY KEY NOT NULL,
    email   TEXT NOT NULL,
    password    TEXT    NOT NULL
);

Ensuite, l'entité doit être annotée avec ceci:

@Entity
@Table(name = "users")
public class User {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(columnDefinition = "serial")
  private Long id;
  private String email;
  private String password;

  public User() {}

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getPassword() {
    return password;
  }

  public void setPassword(String password) {
    this.password = password;
  }
}
8
lbpeppers