无法弄清楚为什么在我的 spring App 中提交注册表单时没有创建我的用户对象。错误:关系“users_seq”不存在

问题描述 投票:0回答:1
Sun Jun 23 19:58:26 EDT 2024
There was an unexpected error (type=Internal Server Error, status=500).
could not extract ResultSet [ERROR: relation "users_seq" does not exist Position: 16] [select nextval('users_seq')]; SQL [select nextval('users_seq')]
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet [ERROR: relation "users_seq" does not exist
  Position: 16] [select nextval('users_seq')]; SQL [select nextval('users_seq')]
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:277)

这是我从中传递数据的 thymeleaf 表单示例:

First Name: <input type="text" th:field="*{firstName}"  />
        <span th:if="${#fields.hasErrors('firstName')}"
              th:errors="*{firstName}"
              class="error"></span>
        <br><br>

        Username:  <input type="text" th:field="*{userName}"  />
        <span th:if="${#fields.hasErrors('userName')}"
              th:errors="*{userName}"
              class="error"></span>
        <br><br>

        Email:     <input type="text" th:field="*{email}"  />
        <span th:if="${#fields.hasErrors('email')}"
              th:errors="*{email}"
              class="error"></span>
        <br><br>

这是使用表单数据的控制器方法:

 @RequestMapping("/signup")
    public String signup(Model theModel) {

        User theUser = new User();
        theModel.addAttribute("user", theUser);

        return "signup";
    }

    @PostMapping("/confirmation")
    public String confirmation(
            @Valid @ModelAttribute("user") User theUser,
            BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "signup";
        } else {

            userService.save(theUser);

            return "confirmation";
        }
    }

第一次使用Spring boot。肯定是傻眼了。不知道哪里需要更改模型。根据我的理解,使用 ModelAttribute 应该在提交表单时自动获取所有字段,对吗?

我的 Postgresql 数据库已创建,其中包含所有必要的列。也有联系。

这也是带有表设置的用户类:

 @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @NotNull(message="Name is required")
    @Size(min=2, message="is required")
    private String firstName;

    @Size(message = "Username should be at least 5 characters")
    @NotNull(message="Username is required")
    private String userName;

    @NotNull(message="Please enter a valid email address.")
    @Email(message = "Not a valid email", regexp = "[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,3}",
            flags = Pattern.Flag.CASE_INSENSITIVE)
    private String email;

    @Min(16)
    @NotNull(message = "Please enter an age above 16.")
    private int age;

    @Min(24)
    @NotNull(message = "Please enter a height above 24 inches.")
    private int height;

    @NotNull(message = "You must select a gender for calorie assignment")
    private String gender;

    @NotNull(message = "Are you so lazy, you don't even wanna pick activity level?")
    private String activityLevel;

    @Min(85)
    @NotNull(message = "You need to enter a weight above 85 pounds.")
    private int weight;

    @ManyToMany
    @JoinTable(
            name = "friends_list",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "friend_id")
    )
    private Set<User> friendsList = new HashSet<>();

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof User)) {
            return false;
        }
        User other = (User) o;
        return id != null && id.equals(other.getId());
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }

    public User() {

    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }


    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }


    public void setActivityLevel(@NotNull(message = "Are you so lazy, you don't even wanna pick activity level?") String activityLevel) {
        this.activityLevel = activityLevel;
    }

    public String getActivityLevel() {
        return activityLevel;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

DDL:

create table users
(
    id            integer not null
        primary key,
    firstname     varchar(255),
    username      varchar(255),
    email         varchar(255),
    age           integer,
    height        integer,
    weight        integer,
    gender        varchar(255),
    activitylevel varchar(255)
);

alter table users
    owner to #####;

将 @GenerateValue(strategy = GenerationType.AUTO) 更改为 @GenerateValue(strategy = GenerationType.IDENTITY) 并获取

2024-06-23T23:25:58.062-04:00 ERROR 5611 --- [fitBuddyApp] [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement [ERROR: column "activity_level" of relation "users" does not exist
  Position: 20] [insert into users (activity_level,age,email,first_name,gender,height,user_name,weight) values (?,?,?,?,?,?,?,?) 
java postgresql spring-boot spring-data-jpa model
1个回答
0
投票

好吧,我明白了。当我在终端上创建表时, 我没有将 id 添加为序列号。

所以我最终创建了一个序列,插入到表中,然后在用户代码中添加了这个花絮。

 @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_gen")
    @SequenceGenerator(name = "user_gen",
            sequenceName = "users_seq", allocationSize = 1)
    private Integer id;

解决了问题。 Postgres 我想 seq 需要与表名匹配。

© www.soinside.com 2019 - 2024. All rights reserved.