0

my entity class trying to implement for stocks.java

@Entity @Table(name="stocks") public Class Stocks { @Id @GeneratedValue @Column(name = "stock_id") private Integer stocked; } 

this my rest API controller I wrote stockcontroller.java

@RestController @RequestMapping("home/stocks") public class HomeController { @Autowired private StockRepo stocks; //POST: adds a new song to the repository @PostMapping("/add") public void addSong(@RequestBody(required = true) Stock stock) throws DuplicateItemException { if(stock.existsById(stock.stockId())) { throw new DuplicateItemException(); } stocks.save(song); } 

}

1
  • It will only be generated when it is persisted, so a new one doesn't have an id. Commented Feb 22, 2022 at 16:34

2 Answers 2

2

You have to define the generation strategy.

For example you can replace @GeneratedValue with:

@GeneratedValue(strategy = GenerationType.IDENTITY) 

or

@GeneratedValue(strategy = GenerationType.SEQUENCE) 

or

@GeneratedValue(strategy = GenerationType.TABLE) 

Of course, you have to put @Transactional on the method addSong to persist the entity.

Sign up to request clarification or add additional context in comments.

Comments

0

change @GeneratedValue to @GeneratedValue(strategy = GenerationType.IDENTITY) or @GeneratedValue(strategy = GenerationType.SEQUENCE)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.