Is it possible to do an insertion in Hibernate when there is the same object reference twice in a list, I want to insert both of them and the ID has to be unique?
I'm using random-beans to generate a random object Person
which has a list of type House
.
The problem is that random-beans doesn't create a new house object every time, it sometimes also uses existing references. In this case the same house object reference can be twice in the person's list.
But regardless of random-beans I would like to handle multiple references of new objects that have to be committed within the same transaction in Hibernate.
Probably this is not possible by the assignment of the ID at Session.save(Object obj)
, as there is still the same object referenced in the list. If there is no trivial solution to this, I would also be thankful for a way to just drop duplicated objects on save or commit. Note that changing the List to a Set doesn't solve the problem, as the same reference can be in different lists.
The database is a MySQL database.
Main
Person steven = new Person();
House house1 = new House();
House house2 = new House();
steven.setHouses(new ArrayList<House>(Arrays.asList(house1, house2, house1));
Session session = getSessionFactory().openSession();
session.beginTransaction();
session.save(steven); // this is where I need to generate 3 different IDs
session.getTransaction().commit(); // this is where a duplicate entry exception is thrown
session.close();
Person
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id_person")
private int id;
@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<House> houses;
House
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id_house")
private int id;
it is not possible, since you have just two instances. You need to create a copy or clone of house1
do something like : house3 = new House(house1);