Java/SpringBoot Web app. Insert new row with auto-incremented id column

Hoodie :

I am trying to store a new row using a few input lines on a web app into an SQL table. My jsp has all the input rows I need. However, I need to store the new object without inputting a new Id because it's auto incremented. I'm able to call my constructor to store everything else but the id. my code for that section so far is:

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

So if I wanted to store "(id)11, (type)bird, (name)patty, (age)5" and I'm only making the type, name, and age inputtable, what should I do for the id? The object technically injects the id as empty I think, but then I get thrown an error. I'm very new to java and Springboot and have very weak skills in both.

pedrohreis :

The magic happens with a JPA implementation (Hibernate, for instance). Just annotate your id field like:

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

When saving the object, the id will be auto-generated and stored.

Check some similar questions: Hibernate Auto Increment ID and How to auto generate primary key ID properly with Hibernate inserting records

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=327363&siteId=1