views:

29

answers:

1

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));
    }
}
+1  A: 

I would call query.list() only once: otherwise the query could be rerun each time:

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);
    List result = query.list();
    for(int i = 0; i < result.size(); i++){
        listOfConflictingProducts.add((Product) result.get(i));
    }
}

Or, more simply:

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(Object obj: query.list()){
        listOfConflictingProducts.add((Product)obj);
    }
}
Maurice Perry
Ahh that's great, thank you for the good tip. Also good to know I was at least headed in the right direction.Thanks much. Accepted.
Slim