問題

我在嘗試在PostgreSQL資料庫中建立新記錄時遇到問題.我只想POST到REST服務一個新使用者(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 List<User> findAll() {
    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 List<User> findAll() {
    return (List<User>) userRepository.findAll();
  }

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

儲存庫

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

請有人幫我,因為我不知道如何解決這個問題.

  最佳答案

我找到了解決方案.我需要更改這些指令碼:

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

  相同標籤的其他問題

javaspringpostgresqljpa