1

Scenario: I do have JSON object as Menus.

//suppose this as 
Menus menus = new Menus();
menus.setId(61);
menus.setUrl("test_url");
menus.setName("menu name");
repository.save(menus);

Current case:

  1. It is working fine if db has menu row with id 61 as a result object gets updated.
  2. While row with id=61 does not exists in db then this menu object gets persisted but with new id. ie. a new row is created with new auto generated ID.

Expected:

  • If menu where id = 61 does not exists in db then menus should be inserted in db with id=61
package com.rasello.auth.entity;

import lombok.*;
import org.hibernate.annotations.Type;

import javax.persistence.*;

@Entity
@Data
@NoArgsConstructor
@Table(name = "menus")
@Getter
@Setter
public class Menus {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;
    
    private String name;

    private String url;

}

1 Answers1

0

Remove this line @GeneratedValue(strategy = GenerationType.TABLE) and try again. The @GeneratedValue does what the words say. Generates value for the ID and in case you do not need that then you should not use it.

You can read more about how to set up your Ids in this article https://www.baeldung.com/hibernate-identifiers

  • In my case I will need auto generated value as well. But current issue is , I need to persist data with predefined id but customid defined by me is overrided by autopopulate. i need some way to override autogeneration. – Sanjay Gyawali Apr 18 '22 at 09:18