2012-02-20 88 views
0

我有一个雇主表用含有userprofileId休眠:无法对象被包含已保存对象

雇主表模式的参考时如所陈述如下含有userprofileid其是使用JPA保存对象用户表中的主键

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表添加相同的值,所以我在employer.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); 

回答

0

你的工作单位是指已经存在的用户配置文件。如果它已经存在,它就在数据库中。如果它在数据库中,则不能创建新的实例,而要从数据库中获取它。要从数据库中获取某些内容,请使用EntityManager.find()EntityManager.getReference()方法(第二个方法甚至不执行任何select语句)。

所以,从你的注释去掉insertableupdatable标志(该协会插入),并使用类似的代码下列之一:

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