为什么delete-orphan需要“cascade all”才能在JPA / Hibernate中运行?

时间:2010-01-29 09:02:16

标签: hibernate jpa cascade

我尝试使用级联“remove”(jpa)和“delete-orphan”映射一对多关系,因为我不希望在保存或保留父级时保存或保留子级(安全性)客户端到服务器的原因(GWT,Gilead))

但是这种配置不起作用。当我尝试使用级联“all”时,它会运行。为什么delete-orphan选项需要级联“all”才能运行?

这是代码(为简单起见没有id或其他字段,Thread类定义了一个简单的多对一属性而没有cascade): 在事务函数中使用removeThread函数时,它不会运行,但如果我将cascade.Remove编辑为cascade.All,它就会运行。

@Entity
public class Forum 
{   
private List<ForumThread>   threads;


/**
 * @return the topics
 */
@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
public List<ForumThread> getThreads()
{
    return threads;
}

/**
 * @param topics the topics to set
 */
public void setThreads(List<ForumThread> threads)
{
    this.threads = threads;
}

public void addThread(ForumThread thread)
{
    getThreads().add(thread);
    thread.setParent(this);
}

public void removeThread(ForumThread thread)
{
    getThreads().remove(thread);
}

}

2 个答案:

答案 0 :(得分:2)

根据Java Persistence with Hibernate,级联孤儿删除不能用作JPA注释。

JPA XML也不支持它。

答案 1 :(得分:0)

对于休眠,REMOVE和DELETE意思相同,请检查。 AnnotationBinder#getCascadeStrategy()

      while ( cascadeType.hasNext() ) {
        switch ( cascadeType.next() ) {
            case ALL:
                cascade.append( "," ).append( "all" );
                break;
            case SAVE_UPDATE:
                cascade.append( "," ).append( "save-update" );
                break;
            case PERSIST:
                cascade.append( "," ).append( "persist" );
                break;
            case MERGE:
                cascade.append( "," ).append( "merge" );
                break;
            case LOCK:
                cascade.append( "," ).append( "lock" );
                break;
            case REFRESH:
                cascade.append( "," ).append( "refresh" );
                break;
            case REPLICATE:
                cascade.append( "," ).append( "replicate" );
                break;
            case EVICT:
                cascade.append( "," ).append( "evict" );
                break;
            case DELETE:
                cascade.append( "," ).append( "delete" );
                break;
            case DELETE_ORPHAN:
                cascade.append( "," ).append( "delete-orphan" );
                break;
            case REMOVE:
                cascade.append( "," ).append( "delete" );
                break;
                }
                        }

所以对于Hiberante来说,REMOVE或DELETE之间没有区别,这是一回事!由于JPA,hibernate,不尊重子元素的CascadeType.DELETE注释,可能是同样的原因,它们也被CascadeType.REMOVE忽略。

如果有帮助(只是猜测)

,请尝试使用CascasdeType.REFRESH