我在尝试在PostgreSQL数据库中创建新记录时遇到问题.我只想向REST服务POST一个新用户(int:id,String:email,String:password)但是,我遇到了这个错误:
"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
这些是我的Java类:
域
@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; } }
调节器
@RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @RequestMapping(method = RequestMethod.GET) public ListfindAll() { return userService.findAll(); } @RequestMapping(method = RequestMethod.POST) public User addUser(@RequestBody User user) { userService.addUser(user); return user; } }
服务
@Service public class UserService { @Autowired private UserRepository userRepository; public ListfindAll() { return (List ) userRepository.findAll(); } public User addUser(User user) { userRepository.save(user); return user; } }
知识库
public interface UserRepository extends CrudRepository{ // TODO }
SQL
CREATE TABLE users( id INT PRIMARY KEY NOT NULL, email TEXT NOT NULL, password CHAR(20) NOT NULL );
请有人帮助我,因为我不知道如何解决这个问题.
我找到了解决方案.我需要更改这些脚本:
CREATE TABLE users( id SERIAL PRIMARY KEY NOT NULL, email TEXT NOT NULL, password TEXT NOT NULL );
然后,实体应该用这个注释:
@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; } }