AutoIncrement Id PostgreSQL 和 Spring Boot Data JPA

2022-09-02 10:46:45

我在尝试在PostgreSQL数据库中创建新记录时遇到问题。我只想将新用户(int:id,String:email,String:password)发布到REST服务,但是,我遇到了这个错误:

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

断续器

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

请有人帮我,因为我不知道如何解决这个问题。


答案 1

我找到了解决方案。我需要更改这些脚本:

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

答案 2

SQL应该是这样的。

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

推荐