【问题标题】:Java/SpringBoot Web app. Insert new row with auto-incremented id columnJava/Spring Boot Web 应用程序。插入具有自动递增 id 列的新行
【发布时间】:2020-02-27 07:44:40
【问题描述】:

我正在尝试使用 Web 应用程序上的几行输入将新行存储到 SQL 表中。我的 jsp 有我需要的所有输入行。但是,我需要在不输入新 ID 的情况下存储新对象,因为它是自动递增的。我可以调用我的构造函数来存储除 id 之外的所有内容。 到目前为止,我对该部分的代码是:

 @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView save
            //Index connect
            (@RequestParam("id") String id, @RequestParam("type") String animalType,
             @RequestParam("name") String animalName, @RequestParam("age") int animalAge){
        ModelAndView mv = new ModelAndView("redirect:/");
        AnimalConstruct newAnimal;

        newAnimal.setAnimalType(animalType);
        newAnimal.setAnimalName(animalName);
        newAnimal.setAnimalAge(animalAge);
        animals.save(newAnimal);
        mv.addObject("animalList", animals.findAll());
        return mv;

因此,如果我想存储“(id)11, (type)bird, (name)patty, (age)5”,而我只是将类型、名称和年龄设为可输入,我该怎么做身份证?我认为该对象在技术上将 id 注入为空,但随后我得到了一个错误。我对 java 和 Springboot 很陌生,两者的技能都很薄弱。

【问题讨论】:

    标签: java mysql spring-boot web-applications


    【解决方案1】:

    在 bean 中使用 id 列注释:

    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private long id;
    

    正如上面@pedrohreis 的回答,您也可以使用GenerationType.AUTO,但前提是您的唯一目的是制作自动增量ID,那么我更喜欢GenerationType.IDENTITY

    此外,如果您想禁用对数据的批量更新,那么您应该使用GenerationType.IDENTITY

    参考:hibernate-identifiers

    【讨论】:

      【解决方案2】:

      当您希望创建对象时,不应传递 ID。

      @RequestMapping(value = "/protected", method = RequestMethod.POST)
      public RouteDocument doPost(@RequestBody RouteDocument route) throws ControllerException {
          createNewRoute(route);
          return route;
      }
      

      在前面的例子中,createNewRoute 方法调用了数据库,在我的例子中使用了 spring JpaTemplate 来保存它。对象路由有一个由 JpaTemplate.save 填充的 ID 属性。因此,doPost 返回对象返回您作为参数传递的相同对象,但具有自动分配的 ID。

      【讨论】:

        【解决方案3】:

        魔术发生在 JPA 实现中(例如 Hibernate)。只需将您的 id 字段注释为:

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

        保存对象时,id会自动生成并保存。

        检查一些类似的问题:Hibernate Auto Increment IDHow to auto generate primary key ID properly with Hibernate inserting records

        【讨论】:

        • 成功了!谢谢!
        猜你喜欢
        • 2018-12-14
        • 1970-01-01
        • 2016-05-05
        • 2020-06-18
        • 2019-06-23
        • 2016-07-27
        • 1970-01-01
        • 2017-05-26
        • 2012-05-29
        相关资源
        最近更新 更多