1

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.

Hoodie
  • 73
  • 6

3 Answers3

3

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

pedrohreis
  • 1,030
  • 2
  • 14
  • 33
1

You should not pass the ID when you expect to create an object.

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

In the previous example, the method createNewRoute, calls the database, in my case using spring JpaTemplate to save it. The object route has an ID property that is filled by JpaTemplate.save. Consequently the doPost return object returns you the same object you passed as parameter BUT with the automatically assigned ID.

user2688838
  • 761
  • 5
  • 11
0

Annotate your id column in the bean with :

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

As answered by @pedrohreis above you can also use GenerationType.AUTO but only if your sole purpose is to make autoincrement id then I prefer GenerationType.IDENTITY

Also, looking forward in your project if you wanna disables batch updates on your data then you should use GenerationType.IDENTITY.

Refer : hibernate-identifiers

Sanket Patel
  • 227
  • 1
  • 14