How to detect column conflicts with Hibernate?
Posted
by Slim
on Stack Overflow
See other posts from Stack Overflow
or by Slim
Published on 2010-04-29T04:59:09Z
Indexed on
2010/04/29
5:37 UTC
Read the original article
Hit count: 241
So let's say I have an ArrayList full of Products that need to be committed to the database via Hibernate. There are already a large number of Products in the database. Each product has an ID. Note this is NOT the PK that is autogenerated by Hibernate.
My questions is: what is the best way to detect conflicts with this ID? I am looking for a relatively efficient method of obtaining, from the the database, a List of Products that share an ID with any of the Products in my ArrayList. This is all in a single table called Products and the ID attribute is in column ProductID.
The way I've done it is grabbing a list of all Products in the database, and compared each one with each entry in my ArrayList - but that is seriously inefficient and I don't think it would work well with a larger database. How should it be done? Thanks. I say "relatively" efficient because efficiency is not the primary concern, but it shouldn't take noticeably long to test against a table of ~1000-5000 rows. Help?
EDIT* I'm very new to hibernate and below is the best I've come up with. How does this look?
for(long id : idList){ //idList just holds the IDs of each Product in my ArrayList
Query query = session.createQuery("select product from Product product where product.id = :id");
query.setLong("id", id);
for(int i = 0; i < query.list().size(); i++){
listOfConflictingProducts.add((Product) query.list().get(i));
}
}
© Stack Overflow or respective owner