AutoIncrement Id PostgreSQL and Spring JPA Boot Data

I am having problems trying to create a new record in my PostgreSQL database. I just want to use POST for the REST service of the new user (int: id, String: email, String: password), but I have this error:

"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 

These are my Java classes:

Domain

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

controller

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

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; } } 

Repository

 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 ); 

Please help me because I do not know how to solve this problem.

+7
java spring postgresql jpa
source share
2 answers

I have found a solution. I need to change the script for this:

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

Then, the Entity should be annotated as follows:

 @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; } } 
+6
source share

SQL should be like that.

 CREATE TABLE users( id INT PRIMARY KEY BIGINT NOT NULL AUTO_INCREMENT, email TEXT NOT NULL, password CHAR(20) NOT NULL ); 
0
source share

All Articles