我希望我的Account
表中的User
共享主键。所以我这样做了:
@Entity
@Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private int userId;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private Account account;
}
@Entity
@Table(name = "account")
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "user_id")
private int userId;
private String password;
private String username;
// bi-directional one-to-one association to User
@OneToOne
@JoinColumn(name = "user_id")
@MapsId
private User user;
}
以下是保存新帐户时的代码。
User user= userService.get(1);
Account account = new Account();
account.username("Loi");
account.password("mypass");
contact.setAccount(account);
account.setUser(contact);
accountService.save(account);
然后我得到了这个例外
org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: com.amashub.tc.models.User; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.amashub.tc.models.User
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:276)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:221)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy65.save(Unknown Source)
我在哪里错过了?