hibernatepostgresqlcascadecascading-deletespostgresql-9.0

ALTER TABLE to add ON DELETE CASCADE statement


I want to do the following in PostgreSQL (using Hibernate):

 ALTER TABLE fruits ADD CONSTRAINTS id ON DELETE CASCADE;

Obviously, my code above is not working, so I am looking for the correct statement.

If I can't do that, then how about the following:

I have a bunch of data in my table fruits. The id field in fruits is used as a foreign key by table grapes. I need to delete a specific row in fruits and I want the deletion to cascade to grapes and delete all entries in grapes that has the specified id. How do I do that?

delete from fruits where id = 1 cascade; 

NOTE: I don't want to do a join and delete the corresponding data in grape. This is just an example. In the real application a large number of tables depend on fruits.

Since I am using Hibernate, for the case when I use a delete statement, can hibernate help do it?
Or can I do this with the information schema or system catalog in PostgreSQL?


Solution

  • I found the answer:

        //in Fruit object
        @OneToMany(mappedBy = "fruit", orphanRemoval=true)
        private List<Grape> grapes;
    
       //in Grape object
       @OneToOne
       private Fruit fruit;