2012-02-20 1 views
0

저장된 객체의 참조를 포함 할 때 JPA를 사용하여 객체를 저장할 수 없습니다 사용자 테이블의 기본 키최대 절전 모드 :이다 userprofileid가 포함되어 아래에 명시된 목적은 내가 userprofileId</p> <p>고용주 테이블을 포함하는 스키마 고용주 테이블이

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를 작성하여 필드가 업데이트되지 않도록했습니다. 내가 고용주 객체의 사용자 프로필의 값을 설정하면

아니오

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); 
관련 문제