当前位置:  开发笔记 > 编程语言 > 正文

AutoIncrement Id PostgreSQL和Spring Boot Data JPA

如何解决《AutoIncrementIdPostgreSQL和SpringBootDataJPA》经验,为你挑选了1个好方法。

我在尝试在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 List 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 findAll() {
    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
);

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



1> lbpeppers..:

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

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


您不需要创建表脚本 - 这些表由JPA自动生成.
推荐阅读
mobiledu2402851323
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有