I have two classes (A and B) where A has a List of B.
Code:
class A {
private java.util.List bList;
// other members and methods not important
}
class B {
// members and methods not important
}
The database tables for these two classes would be:
Code:
create table A (
id VARCHAR(36) NOT NULL,
// other A columns
)
create table B (
id VARCHAR(36) NOT NULL,
a_id VARCHAR(36) NOT NULL,
// other B columns
)
In the 'B' table, the a_id has a foreign key relationship with the id column of the 'A' table.
My question is this: I have a detached instance of A that is populated with several instances of B in its bList. I want to delete all of the instances of B from the instance of A without deleting A. If I were writing strait JDBC code, I would use the following SQL:
Code:
delete from B where a_id = [the id value of A's id];
What is the best way to do the same with Hibernate? I know of two ways, neither of which is attractive:
Method #1:
Code:
session.delete("from B as b where b.aId = " + a.id);
The problem with this is that all of the Bs will first be selected from the database before they are deleted. This seems silly because I already have all of the B data in memory within A's bList (remember that I have detached instances). Why would I want to re-select them just to delete them?
Method #2:
Code:
for (Iterator i = a.getBList(); i.hasNext(); ) {
B b = (B)i.next();
session.delete(b);
}
This would work fine, except that it will issue one SQL delete statement per instance of B. This also seems silly considering that if I were using JDBC, I would do the same with one SQL delete statement as described above.
So, finally, how do I make Hibernate remove all of the elements of a collection, without removing the collection's parent, in one single SQL delete call?
Thanks!
Hibernate version:2.1.7