I am trying to bulk insert a List
of objects. I have the ID configured to be auto generated. Previously I had the following:
<id name="entryId" type="integer" column="ENTRY_ID">
<generator class="seqhilo">
<param name="sequence">HB_ENTRY_ID_SEQ</param>
<param name="max_lo">50</param>
</generator>
</id>
And my insert query was as follows:
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
for (int i = 0; i < insertList.size(); i++) {
session.save(insertList.get(i));
if (i % 100 == 0) {
session.flush();
session.clear();
}
}
session.getTransaction().commit();
return insertList.size();
}
I have the correct batch_size
property value set as well. The above worked fine, however, recently I changed my code to be annotation based and I have the following:
@Id
@Column(name = "ENTRY_ID")
@GeneratedValue(generator = "hibSeq", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "hibSeq", sequenceName = "HB_ENTRY_ID_SEQ", allocationSize = 100)
When I run this now, the insert throws a org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session
I've been trying to understand this error as per here and here but haven't been able to resolve my issue. As far as I can tell, something is happening at the session.flush()/clear()
stage that causes the sequence generator to recycle an ID that has already been used.
What am I doing wrong?