我正在学习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