有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果父表包含一个序列号,如何使用Hibernate保存两个数据库表?

我使用{}和{}在{}web应用程序中工作。我需要在一个需要serial列的复杂解决方案中,在同一个transaction中保存两个表。下一个例子是一个基本的例子,我可以解释我真正的问题:

这是数据模型;一个ObjectTable2有许多Objects{},同时在Table2many行中插入一个row非常重要,参考(FK)到Table2

enter image description here

[Table1.column_fk是intserial,图像错误]

我的问题是我不知道Table2.column_pk的值,因此我无法轻松地保存在Table1中,因为我不会请求一个query咨询(Table2 objTable2 = session.createQuery("SELECT t2 from Table2 order by column_pk desc").list().get(0);),然后为每个Table1 objectsobjTable1_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) 个答案