我正在學習hibernate,並且我有一個hibernate類TestAuthor,並且使用'HibernateUtil.getCurrentSession()。persist'命令將記錄插入到該類中,如下面的代碼所示。 問題是,當我運行該代碼,然後檢查表中的條目時,我發現onlx最後一條記錄被插入。換句話說,在運行下面的代碼之後,TestAuthor表只包含插入的最後一條記錄 ,它是'testAuthor.setmFName(「Nour」); testAuthor.setmLName( 「Youssri」);」如何順序插入多行
爲什麼只有最後一行被插入而另一個被忽略,以及如何解決這個問題?
Hibernate代碼:
TestAuthor testAuthor = new TestAuthor();
testAuthor.setmFName("Ali");
testAuthor.setmLName("gamil");
HibernateUtil.getCurrentSession().persist(testAuthor);
testAuthor.setmFName("Fatma");
testAuthor.setmLName("Joss");
HibernateUtil.getCurrentSession().persist(testAuthor);
testAuthor.setmFName("Lobna");
testAuthor.setmLName("Nolan");
HibernateUtil.getCurrentSession().persist(testAuthor);
testAuthor.setmFName("Ahmed");
testAuthor.setmLName("Ghadi");
HibernateUtil.getCurrentSession().persist(testAuthor);
testAuthor.setmFName("Nour");
testAuthor.setmLName("Youssri");
HibernateUtil.getCurrentSession().persist(testAuthor);
更新
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 Integer mAuthorID;
@Column(name = "FNAME")
private String mFName;
@Column(name = "LNAME")
private String mLName;
@OneToMany(mappedBy = "author")
private List<TestBook> books;
public Integer getmAuthorID() {
return mAuthorID;
}
public void setmAuthorID(Integer 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() {
// TODO Auto-generated constructor stub
}
}
不要重複使用同一個對象來表示不同的數據行。爲每一行創建一個新的TestAuthor。 – JonK