本人新手,在做整合时,各种问题不停………..求大哥..
user 和 subject是one-to-many的双向关系,
但在保存subject时,出现
Exception in thread “main” org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: cc.struts.domain.User; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: cc.struts.domain.User
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:648)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.persist(HibernateTemplate.java:804)
at cc.service.test.UserAndSubjectTest.main(UserAndSubjectTest.java:29)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: cc.struts.domain.User
at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:102)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:637)
……………………………
应该是id什么错误了,可我不知道错在那,我用的是mySql,
下面是用到的表
@Entity
public class User {
private Date birthday;
private String email;
private int id;
private String passWorld;
private String phone;
private String userName;
private List<Subject> subjects;
@OneToMany(mappedBy=”user”,targetEntity=Subject.class,cascade=CascadeType.ALL)
public List<Subject> getSubjects() {
return subjects;
}
public void setSubjects(List<Subject> subjects) {
this.subjects = subjects;
}
/*主键*/
@Id
@GeneratedValue
public int getId() {
return id;
}
public String getPassWorld() {
return passWorld;
}
public String getPhone() {
return phone;
}
public String getUserName() {
return userName;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void setEmail(String email) {
this.email = email;
}
public void setId(int id) {
this.id = id;
}
//…其它getXxx,setXxx.
}
@Entity
public class Subject {
private int id;
private String title;
private Date time;
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
private User user;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(cascade=CascadeType.ALL)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
//…其它getXxx,setXxx.
}