2012-08-14 141 views
1

我有2種實體類如下:休眠4實體映射與Spring

@Entity 
@Table(name = "USER_ACCT") 
public class UserAccount implements Serializable{ 

private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="USER_ACCT_ID_SEQ") 
@SequenceGenerator(name="USER_ACCT_ID_SEQ", sequenceName="USER_ACCT_ID_SEQ") 
@Column(name = "USER_ACCT_ID") 
protected Long id; 

@Basic(optional = false) 
@Column(length = 50, unique = true) 
private String username; 

@Basic(optional = false) 
@Column(length = 128, nullable = false) 
private String password; 

@ManyToMany(targetEntity = UserPermission.class) 
@JoinTable(name = "USER_ACCT_PERM", 
     joinColumns   = @JoinColumn(name = "USER_ACCT_ID"), 
     inverseJoinColumns = @JoinColumn(name = "USER_PERM_ID", referencedColumnName = "USER_PERM_ID")) 
private Set<UserPermission> permissions; 

// getters and setters... 
} 

@Entity 
@Table(name = "USER_PERM") 
public class UserPermission implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @Id 
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="USER_PERM_ID_SEQ") 
    @SequenceGenerator(name="USER_PERM_ID_SEQ", sequenceName="USER_PERM_ID_SEQ") 
    @Column(name = "USER_PERM_ID") 
    protected Long id; 

    @Column(name = "PERM", unique = true, length = 255, nullable = false) 
    private String authority; 
// getters and setters... 
} 

現在,當我創建UserAccount的對象,並嘗試使用該會話進行保存它給我以下錯誤:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.rpm.domain.UserPermission 

不應該UserPermission類自己保存??? 這是一個用於保存代碼:

@Transactional 
    public void addUser(){ 
       Set<UserPermission> permissions = new HashSet<UserPermission>(); 
    permissions.add(new UserPermission("ROLE_ADMIN");); 
     sessionFactory.getCurrentSession().save(new UserAccount("admin", "d033e22ae348aeb5660fc2140aec35850c4da997", permissions)); 
    } 
+0

也許如果你發佈你用來創建和堅持實體的代碼,我們可以幫助你更好 – 2012-08-14 19:09:48

回答

1

除非你指定的級聯選項。

+0

@Batman樂於! – Eugene 2012-08-15 04:26:00