Home > OS >  @GeneratedValue not generating id value in entity class
@GeneratedValue not generating id value in entity class

Time:02-23

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);
}

}

CodePudding user response:

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.

CodePudding user response:

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

  • Related