jbx
jbx

Reputation: 22138

JPA 2.0 native annotations for cascading deletes of a one-way relationship

This question is related to this in relation to the fact that I have a one-way @ManyToOne relationship between child and parent. There are hundreds of thousands of child entries, and I do not want the parent to have a @OneToMany relationship with the children.

All works fine except for the fact that deleting the parent is not possible unless I delete the children first, and I am looking to achieve what Postgres easily provides through the ON DELETE CASCADE. I am using Postgres 9. I am also using JPA 2.0/Hibernate 4.1.7.

I am currently using the auto DDL creation feature of Hibernate, because I am frequently moving things around, so I don't want to manually add the ON DELETE CASCADE on the tables, because they will be deleted the next time round I do some changes.

Is there any way I can put the ON DELETE CASCADE constraint/trigger as part of the JPA @ManyToOne annotations in the child Entity? This way the database is created correctly automatically.

Upvotes: 3

Views: 1876

Answers (1)

Steve Ebersole
Steve Ebersole

Reputation: 9443

Using JPA annotations, no. But Hibernate has @org.hibernate.annotations.OnDelete.

    @ManyToOne
    @JoinColumn
    @OnDelete( action = OnDeleteAction.CASCADE )
    private Parent parent;

The EG is discussing adding something similar this as part of JPA 2.1

Upvotes: 5

Related Questions