开发者

Hibernate cascading

开发者 https://www.devze.com 2022-12-25 18:10 出处:网络
All what Hibernate reverse engineering generates is something like this @ManyToOne(fetch = FetchType.LAZY)

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?


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号