Auto generate id in Spring MVC

前端 未结 1 1466
情书的邮戳
情书的邮戳 2021-01-12 16:19

I\'m trying to save data collected by a JSP page within a database (Postgres). At first I tried to insert any values manually (including id) in a form and I had

1条回答
  •  有刺的猬
    2021-01-12 16:58

    Now I'm trying to auto generate the id values, but I'm a little bit confused about how to do it properly

    If you want to automatically generate the id, then do not provide one, even it's null. So, remove the id from addProduect method:

    @Override
    public void addProduct(String description, double price, Date date) {
        jdbcTemplate.update("INSERT INTO products values(?, ?, ?)", description, price, date);
    }
    

    Also, make your id field auto-increment, as in this question.

    Or, change the addProduct method and use EntityManager#persist method:

    @Override
    public void addProduct(Product product) {
        entityManager.persist(product);
    }
    

    About the error:

    ERROR: null values in column "id" violates not-null constraint

    Since your form does not take the id value from the client, the /newproduct endpoint would have a Product with null as its id value:

    @RequestMapping(value = "/newproduct", method = RequestMethod.POST)
    public ModelAndView submitForm(@ModelAttribute("product") Product product) { ... }
    

    Then you pass this null value as the parameter to the addProduct method:

    prDao.addProduct(product.getId(), ...)
    

    And finally addProduct would try to save that null value as the value of the Primary Key, which has a Non-Null constraint, so you're got that error.

    Also, using Entity objects as the means of communication with client, e.g. Product, is not a good practice. Try to define some auxiliary abstractions like Forms or DTOs and use them for form handling or response assembling.

    0 讨论(0)
提交回复
热议问题