I’m creating a user and role association with ManyToOne & OneToMany mappings. I’m executing this thru a rest API to persist data. The issue is that when I run API multiple times, the same role is created multiple times in role table. Below the details. Please help.
Issue here - same role is created multiple times, which should not be ideally.
Hibernate is just doing what your code is instructing it to. You always save a new
Role
on each call. If you want to update an existing
Role
, you will have to implement that by looking up the
Role
by e.g.
name
and if that exists, update that, otherwise create a new one. Beware that it is still possible to create duplicate
Role
s though. If you want to avoid this, you should create a unique constraint on e.g.
name
so that the database makes sure the duplicate can never be inserted.