2012-02-20 67 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);