Patrick McDaniel
Patrick McDaniel

Reputation: 1083

How to delete all children in a foreign key relationship

I have two tables in my database USERS, and USER_SESSIONS. USER_SESSIONS has a foreign key on userid that maps to the USERS table's userid, and I have defined the many-to-one relationship in hibernate with:

<many-to-one name="user" column="USERID" class="com.Users" />

How do I write a hibernate method to delete all rows in the USER_SESSIONS database for a given user when only given the username.

My first attempt was to load the user object for the given username, and then do an HSQL to delete all sessions for that user's userid. Is there a simpler way?

Upvotes: 0

Views: 1408

Answers (1)

Yogendra Singh
Yogendra Singh

Reputation: 34367

I think one other way could be as:

  1. Define cascade as delete on the relationship
  2. Load user entity
  3. Remove all the user session object from user
  4. Save user entity back.

Upvotes: 2

Related Questions