保存实体时,Hibernate会抛出TransientPropertyValueException

时间:2014-08-01 03:57:34

标签: java hibernate orm entity hibernate-mapping

我有两个相关的实体,即机构和注册,这样注册和机构之间就存在多对一的关系。因此,我们应该能够为一个机构提供注册条目。

实体和关系映射:

@Entity
public class Registration{

    @NotNull @ManyToOne(optional=false)
        @JoinColumn(updatable=false, insertable=false)
        private Institution institution;

}


@Entity
public class Institution{
    @OneToMany(cascade={CascadeType.REMOVE, CascadeType.MERGE}, fetch=FetchType.EAGER, mappedBy="institution", orphanRemoval=true)
        private Set<Registration> registrations;
}

并且错误跟踪可用here

[INFO] 04:34:26,043 WARN  [org.hibernate.action.internal.UnresolvedEntityInsertActions] (http-localhost/127.0.0.1:8888-4) HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities.
[INFO]  Unsaved transient entity: ([com.bitrunk.apps.nussa.client.shared.Institution#<null>])
[INFO]  Dependent entities: ([[com.bitrunk.apps.nussa.client.shared.Registration#<null>]])
[INFO]  Non-nullable association(s): ([com.bitrunk.apps.nussa.client.shared.Registration.institution])
[INFO] 04:34:26,046 ERROR [stderr] (http-localhost/127.0.0.1:8888-4) java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: Not-null property references a transient value - transient instance must be saved before current operation: 

错误是:由以下原因引起:org.hibernate.TransientPropertyValueException:非null属性引用瞬态值 - 必须在当前操作之前保存瞬态实例:Registration.institution - &gt;机构

这很奇怪,因为在注册过程中,用户使用下拉窗口小部件从DB中已有的条目中选择他/她的机构,这样Register.institution应该指向DB中的对象,这使得我想知道这个错误是什么以及如何修复它。

我需要像昨天一样修复。谢谢大家。

2 个答案:

答案 0 :(得分:1)

您当前的映射并未设置注册/机构协会的所有者。

  1. 如果您希望注册控制关联(最常见),那么这是您的映射:

    @Entity
    public class Registration{
    
        @NotNull 
        @ManyToOne(optional=false)      
        private Institution institution;
    
    }
    
    
    @Entity
    public class Institution{
        @OneToMany(cascade={CascadeType.REMOVE, CascadeType.MERGE}, fetch=FetchType.EAGER, mappedBy="institution", orphanRemoval=true)
        private Set<Registration> registrations;
    }
    
  2. 如果您希望机构控制关联(不常见),那么您的映射将成为:

    @Entity
    public class Registration{
    
        @NotNull 
        @ManyToOne(optional=false)
        @JoinColumn(updatable=false, insertable=false)          
        private Institution institution;
    
    }
    
    
    @Entity
    public class Institution{
        @OneToMany(cascade={CascadeType.REMOVE, CascadeType.MERGE}, fetch=FetchType.EAGER, orphanRemoval=true)
        private Set<Registration> registrations;
    }
    
  3. 你不能同时设置(updatable=falseinsertable=false)和mappedBy,因为这种关联都不能控制关联,告诉Hibernate在同步对象状态时调查哪一方数据库。

答案 1 :(得分:0)

仔细检查下拉窗口小部件中的Institution个实例:它们可能是已获取实例的副本。