0

I have the following query to delete an item in a table when a user presses a button

  String hqery = "DELETE FROM Person WHERE automobile = " selected_id;
  Query q = hbsession.createQuery(hquery);
  q.executeUpdate();

The variables in the Person class are:

int id;
String name;
int age;
Cars automobile;

And the variables in the Cars class are:

int id;
String Manufacturer
String Model;
int Year;

The problem is automobile is an instance of the Bean class Cars, how do I delete a class using a query or how can I access the ID of automobile so that I can delete it. The reason I want to do this is because when I delete a car from the car table I need to also delte all instances of the car in other tables.

abden003
  • 1,325
  • 7
  • 24
  • 48

1 Answers1

2

The reason I want to do this is because when I delete a car from the car table I need to also delte all instances of the car in other tables.

You need to either create foreign keys in the database with ON DELETE CASCADE set, or use Hibernate's orphan deletion features for dependent objects.

I recommend using a combination. Create FOREIGN KEY references in the database but set them to ON DELETE RESTRICT. Then manage the relationships in Hibernate with orphan removal, etc. The database checks will make sure that if you miss something at the Hibernate level you won't land up with inconsistent data in the database; instead you'll get a database error when you run the query or attempt to commit.

See:

Community
  • 1
  • 1
Craig Ringer
  • 307,061
  • 76
  • 688
  • 778