views:

138

answers:

2

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?

+1  A: 

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.

joekutner
+1  A: 

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.

Péter Török