EugeneP
EugeneP

Reputation: 12003

Hibernate cascading

All what Hibernate reverse engineering generates is something like this

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "column_id")
    public Itinerary getColumnId() {
        return this.columnId;
    }

I want this scenario: when session flushes, first all constructed childs were saved, then the parent object, according to FK constraints.

Of course, children need to be saved first (automatically!), 'cause there are FK constraints.

You'd tell me: there's a CASCADE option, but how to use it with JPA?

I tried adding cascade like this:

    @ManyToOne(fetch = FetchType.LAZY, cascade=CascadeType.PERSIST)
    @JoinColumn(name = "column_id")
    public Itinerary getColumnId() {
        return this.columnId;
    }

Does not work for me.

Tell me first: what should be annotated with this directive and how to get it worked.

I'm getting "Cannot add or update a child row: a foreign key constraint fails" exception.

And indeed, I do not want to persist everything by hand ! Only construct ONE object and persist it!

What to annotate, what directive to use and how?

Upvotes: 3

Views: 4589

Answers (3)

u1957752
u1957752

Reputation: 26

You should combine JPA and Hibernate's private annotations. See documentation.

Upvotes: 0

Péter Török
Péter Török

Reputation: 116246

Try putting the cascade annotation to the parent end of the mapping, like

@OneToMany(cascade = { CascadeType.PERSIST, 
                       CascadeType.MERGE, 
                       CascadeType.REMOVE },
           mappedBy = "children")
private Set<Children> children = new HashSet<Children>();

You may or may not need all those cascading options - pick your choice.

Here is a reference page just in case.

Upvotes: 3

codefinger
codefinger

Reputation: 10318

What you really need is

cascade=CascadeType.SAVE_UPDATE

But thats not part of JPA. So you can use this instead:

cascade=CascadeType.ALL

It will include SAVE_UPDATE (with the Hibernate implementation). But it may include other cascades you don't like.

Upvotes: 1

Related Questions