【问题标题】:Hibernate: unable to save object using JPA when object is containing reference of saved object休眠:当对象包含已保存对象的引用时,无法使用 JPA 保存对象
【发布时间】:2012-02-20 11:59:29
【问题描述】:

我有一个包含 userprofileId 架构的雇主表

如下所述的employees表包含userprofileid,它是user表的主键

id                 int(11)      (not NULL)         PRI        
userprofileid      int(11)      (not nUll)                          
organization_name  varchar(50)  (not nUll)  

现在我的要求是为这个雇主创建一个 JPA 类。

现在我们有了 Employer.java,有以下条目。

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(fetch=FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name="userProfileId", referencedColumnName="id" )
    @Column( insertable=false ,updatable =false)
    private UserProfile userProfile;

    @Column(name = "organization_name")
    private String organizationName;

现在的障碍是。 我们的 UserProfile 对象是用不同的方法创建的。现在我不想再次向 userprofile 表添加相同的值,所以我在 employees.java 中设置了 insertable = false 和 updatable = false 以便该字段不会被更新;

如果我在雇主对象中设置 userprofile 的值,则否

它说

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.hcentive.core.user.UserProfile; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.hcentive.core.user.UserProfile

但如果我不设置用户配置文件,则会出现以下错误。

Caused by: java.sql.SQLException: Field 'userprofileid' doesn't have a default value

注意我正在使用的坚持:

getJpaTemplate().persist(t);

【问题讨论】:

    标签: hibernate jpa-2.0 hibernate-mapping


    【解决方案1】:

    您的雇主指的是已经存在的用户个人资料。如果它已经存在,则它在数据库中。如果它在数据库中,则不能创建新实例,而是从数据库中获取它。要从数据库中获取某些内容,您可以使用EntityManager.find()EntityManager.getReference() 方法(第二个甚至不执行任何选择语句)。

    因此,从注释中删除insertableupdatable 标志(关联可插入的),并使用类似于以下的代码:

    UserProfile up = em.getReference(UserProfile.class, userProfileId);
    employer.setUserProfile(up);
    em.persist(employer);
    

    【讨论】:

      猜你喜欢
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2012-08-09
      • 2015-04-27
      • 2012-12-06
      • 2017-05-14
      • 2017-01-08
      相关资源
      最近更新 更多