在DB中插入持久性记录,其中两个表是分开的

时间:2014-08-18 11:26:42

标签: hibernate struts

我正在使用strutshibernate。我试图在两个独立的表中插入数据。如果第一个表插入创建任何错误,我无法插入第二个表数据,反之亦然。我想这样做。我怎么能这样做?

public String create() {
    getDaoFactory().instantiateDAO(daoClass).saveOrUpdate(entity);
    getDaoFactory().getMatchPredictionOptionLevel2().saveOrUpdate(
                    optionLevel2);
   return SUCCESS:

}

public T saveOrUpdate(T entity) {
        try {
            getSessionTx().save(entity);
            commit();
        } catch (Exception e) {
            rollback();
            e.printStackTrace();
        } finally {
            getSession().close();
        }
        return entity;
    }

public Session getSessionTx() {
        System.out.println("In Get Sassion Method getSessionTx");
        if (this.session == null)
            this.session = HibernateUtil.getSessionFactory().openSession();

        this.session.beginTransaction();
        return this.session;
    }

1 个答案:

答案 0 :(得分:0)

这就是Transactions的目的。

For Instance:

        try{
            session = HibernateUtil.getSessionFactory().openSession();//<==Creade Session from SessionFactory

            tx = session.beginTransaction();//<==== Start Transacton
            tx.setTimeout(5);
            //doSomething(session); if one of the queries fail to insert it goes to catch 
            tx.commit();

        }catch(RuntimeException e){
            try{
                tx.rollback();//<=== you'll be rolling back the previous inserting value in case if one failed to insert
            }catch(RuntimeException rbe){
                log.error("Couldn’t roll back transaction", rbe);
            }
            throw e;
        }finally{
            if(session!=null){
                session.close();
            }

详细了解Here