我在下面发布了两个hibernate类,我试图使用populateAuthorTable方法中提到的代码将记录插入到TestAuthor表中,该方法也在下面发布。 当我运行我收到的代码时
detached entity passed to persist: msc.hibernate.persistence.TestAuthor
请让我知道如何解决此错误
populateAuthorTable :
private void populateAuthorTable() {
// TODO Auto-generated method stub
Session session = HibernateUtil.getCurrentSession();
Transaction transaction = session.beginTransaction();
ArrayList<TestAuthor> authorsList = new ArrayList<>();
for (Long i = (long) 0; i < 30; i++) {
authorsList.add(new TestAuthor(i, "FName_" + i, "LName_" + i));
}
int i = 0;
for (TestAuthor ta : authorsList) {
session.persist(ta);
i++;
}
}
TestAuthor :
@Entity
@Table(schema = "afk_owner", name = "testauthor")
public class TestAuthor {
@Id
@Column(name = "authorid")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequencegen")
@SequenceGenerator(name = "sequencegen", sequenceName = "afk_owner.testauthor_seq", allocationSize = 1)
private Long mAuthorID;
@Column(name = "FNAME")
private String mFName;
@Column(name = "LNAME")
private String mLName;
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<TestBook> booksList;
public Long getmAuthorID() {
return mAuthorID;
}
public List<TestBook> getBooksList() {
return booksList;
}
public void setBooksList(List<TestBook> booksList) {
this.booksList = booksList;
}
public void setmAuthorID(Long mAuthorID) {
this.mAuthorID = mAuthorID;
}
public String getmFName() {
return mFName;
}
public void setmFName(String mFName) {
this.mFName = mFName;
}
public String getmLName() {
return mLName;
}
public void setmLName(String mLName) {
this.mLName = mLName;
}
public TestAuthor() {
}
public TestAuthor(Long id, String fName, String lName) {
this.mAuthorID = id;
this.mFName = fName;
this.mLName = lName;
this.booksList = new ArrayList<>();
}
}
答案 0 :(得分:0)
当你设置一个新对象的@Id字段时,hibernate会认为它是一个独立的实体。您创建的序列生成器的要点是为新实体生成ID。只是没有设置ID,它应该工作。非常粗略的解决方案:
public TestAuthor(Long id, String fName, String lName) {
//this.mAuthorID = id;
this.mFName = fName;
this.mLName = lName;
this.booksList = new ArrayList<>();
}
通常,当您的对象真正分离时,您会收到此错误,而不仅仅是错误地启动了新对象。