本文介绍了Hibernate级联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有Hibernate的逆向工程生成的东西都是这样的

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

我想要这个场景:当会话刷新时,首先保存所有构造的子元素,然后根据FK限制。



当然,孩子需要先保存(自动!),因为有FK限制。

你会告诉我:有一个CASCADE选项,但是如何在JPA中使用它?



我尝试了像这样添加级联:

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

不适合我。



告诉我第一:应该用这个指令注释什么,以及如何让它工作。



我得到无法添加或更新子行:外键约束失败例外。



事实上,我不想用手坚持一切!只构造一个对象并且
坚持它!



要注释什么,使用什么指令以及如何使用?

解决方案

尝试将级联注释放在映射的父端,如

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

您可能需要也可能不需要所有这些级联选项 - 选择您的选择。



这是一个以防万一。


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 andpersist 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.

这篇关于Hibernate级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:09