java如果父表包含一个序列号,如何使用Hibernate保存两个数据库表?
我使用{serial
列的复杂解决方案中,在同一个transaction
中保存两个表。下一个例子是一个基本的例子,我可以解释我真正的问题:
这是数据模型;一个Object
的Table2
有许多Objects
{Table2
和many
行中插入一个row
非常重要,参考(FK
)到Table2
:
[Table1.column_fk是int
否serial
,图像错误]
我的问题是我不知道Table2.column_pk
的值,因此我无法轻松地保存在Table1
中,因为我不会请求一个query
咨询(Table2 objTable2 = session.createQuery("SELECT t2 from Table2 order by column_pk desc").list().get(0);
),然后为每个Table1 objects
(objTable1_1.setTable2(objTable2); objTable1_2.setTable2(objTable2); ...
)添加它的column_pk
。我相信Hibernate
对于这种情况有简单的方法
例如,这可能是Java
简单代码:
表1。爪哇:
public class Table1{
private int columnPk;
private String columnX;
private Table2 table2;
public Table1(String columnX){
this.columnX = columnX;
}
public int getColumnPk() {
return columnPk;
}
public void setColumnPk(int columnPk) {
this.columnPk = columnPk;
}
public String getColumnX() {
return columnX;
}
public void setColumnX(String columnX) {
this.columnX = columnX;
}
public Table2 getTable2() {
return table2;
}
public void setTable2(Table2 table2) {
this.table2 = table2;
}
}
表2。爪哇:
public class Table2{
private int columnPk;
private String columnX;
public Table2(){
}
public int getColumnPk() {
return columnPk;
}
public void setColumnPk(int columnPk) {
this.columnPk = columnPk;
}
public String getColumnX() {
return columnX;
}
public void setColumnX(String columnX) {
this.columnX = columnX;
}
}
使用Hibernate执行以下操作:
public void saveAll() throws Exception {
Session session = NewHibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
try {
Table2 objTable2 = new Table2();
List<Table1> listTable1 = new ArrayList<Table1>();
objTable2.setColumnX("text");
save(objTable2);
//In this line, I need collect objTable2 with serial assigned
for(int i = 0; i < 5; i++){
listTable1.add(new Table1("text"));
//In this line I should add the Table2: listTable1.get(i).setTable2(objTable2);
//In this line I should to save the objsTable1: save(listTable1.get(i));
}
transaction.commit();
session.close();
} catch (Exception e) {
throw e;
}
}
请考虑其他一切都是完美的。
谢谢大家!
共 (0) 个答案