Hi,
I use Hibernate and I try to delete parent object using cascade property
These are my two java classes: Address(parent) and Student(child)
Code:
public class Address implements java.io.Serializable {
private long addressId;
private String street;
private String city;
private String state;
private String zipcode;
private Set students;
...
public class Student implements java.io.Serializable {
private long studentId;
private String studentName;
...
and mapping files:
Code:
<class name="com.vaannila.student.Student" table="STUDENT">
<meta attribute="class-description">This class contains student details.</meta>
<id name="studentId" type="long" column="STUDENT_ID">
<generator class="native" />
</id>
<property name="studentName" type="string" length="100" not-null="true" column="STUDENT_NAME" />
</class>
<class name="com.vaannila.student.Address" table="ADDRESS">
<meta attribute="class-description">This class contains the student's address
details.</meta>
<id name="addressId" type="long" column="ADDRESS_ID">
<generator class="native" />
</id>
<property name="street" column="ADDRESS_STREET" type="string" length="250" />
<property name="city" column="ADDRESS_CITY" type="string" length="50" />
<property name="state" column="ADDRESS_STATE" type="string" length="50" />
<property name="zipcode" column="ADDRESS_ZIPCODE" type="string" length="10" />
<set name="students" cascade="all">
<key column="parent_id"/>
<one-to-many class="com.vaannila.student.Student" />
</set>
</class>
I have two problems with it:
1) I have only id of Address object and I want to delete it. The only way I see is to load this object from the database before I can remove it. I can't type the following statement
Code:
session.createQuery("delete from Address as a where a.addressId=" + 1).executeUpdate();
because tables in the database are created by hibernate (hbm2ddl.auto) and they don't have "on delete cascade" option. Is there any method to delete Address object with one query when I know only its id?
2) I delete Address object and because of cascade property set to "all" in my mapping file hibernate removes all Student objects associated with it. However, there is a similar situation as in 1). Hibernate needs to load all Student objects which are going be removed. For 2 records in the database it's ok, but for 10000 records it's completely suboptimal. The same question: is there any way to prevent this situation?
Thanks in advance !