I have a hierarchy of classes with a single table per hierarchy but with joined secondary tables. Legacy DB schema has tables with cascade on delete. Therefore, to delete a record for a child it was enough to delete the associated record for the parent.
My question is how to tell Hibernate to use this feature?
To illustrate it, I created an example of classes and tables:
This is a parent class
Code:
[color=blue]@javax.persistence.Entity(name="Person")
@javax.persistence.Table(name="person")
@javax.persistence.DiscriminatorColumn(name="type")
@javax.persistence.Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Person
{
int id;
String type;
@javax.persistence.Id
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
@javax.persistence.Basic
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
}[/color]
And this is a child
Code:
[color=blue]@Entity(name = "Customer")
@SecondaryTables(@SecondaryTable(name = "customer", pkJoinColumns = {
@PrimaryKeyJoinColumn(name = "id")}))
@DiscriminatorValue(value = "customer")
public class Customer extends Person
{
String account;
@javax.persistence.Basic
@Column(table = "customer")
public String getAccount()
{
return account;
}
public void setAccount(String account)
{
this.account = account;
}
} [/color]
DB Schema looks like:
Code:
[color=blue] CREATE TABLE `person` (
`id` int(11) NOT NULL,
`type` varchar(30) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `customer` (
`id` int(11) NOT NULL,
`account` varchar(30) default NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`id`) REFERENCES `person` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB; [/color]
If I issue sql command to DB:
Code:
[color=blue]delete from person where id=1;[/color]
it will delete records from person and from customer tables. I would expect Hibernate to do the same. However, if I execute HQL query through Hibernate:
Code:
[color=blue]delete Person where id=1[/color]
it will generate something like this:
Code:
[color=blue]create temporary table if not exists HT_person (id integer not null);
insert into HT_person select p.id as id from person p left outer join customer p1_ on p.id=c.id where type='customer' and (p.id=1)
delete from customer where (id) IN (select id from HT_person)
delete from person where (id) IN (select id from HT_person)
drop table HT_person[/color]
On large tables with many children it becomes a problem. So one more time, is it possible to teach Hibernate to use DB cascade delete?
Thank you,
Yevgeny