org.hibernate.Transaction.commit()

Here are the examples of the java api org.hibernate.Transaction.commit() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

862 Examples 7

18 Source : UserDAO.java
with Apache License 2.0
from yugabyte

@Override
public void save(final User enreplacedy) {
    Session session = openCurrentSession();
    Transaction transaction = session.beginTransaction();
    try {
        session.save(enreplacedy);
        transaction.commit();
    } catch (RuntimeException rte) {
        transaction.rollback();
    }
    session.close();
}

18 Source : ProductDAO.java
with Apache License 2.0
from yugabyte

@Override
public void save(Product enreplacedy) {
    try (Session session = openCurrentSession()) {
        Transaction transaction = session.beginTransaction();
        try {
            session.save(enreplacedy);
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
        } finally {
            transaction.commit();
        }
    }
}

18 Source : OrderLineDAO.java
with Apache License 2.0
from yugabyte

@Override
public void save(OrderLine enreplacedy) {
    try (Session session = openCurrentSession()) {
        Transaction transaction = session.beginTransaction();
        try {
            session.save(enreplacedy);
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
        } finally {
            transaction.commit();
        }
    }
}

18 Source : OrderDAO.java
with Apache License 2.0
from yugabyte

@Override
public void save(Order enreplacedy) {
    try (Session session = openCurrentSession()) {
        Transaction transaction = session.beginTransaction();
        try {
            session.save(enreplacedy);
        } catch (Exception e) {
            e.printStackTrace();
            transaction.rollback();
        } finally {
            transaction.commit();
        }
    }
}

18 Source : UserDao.java
with MIT License
from yocaning

// 修改用户
public void updateUser(UserBean user) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    session.update(user);
    ts.commit();
    session.close();
}

18 Source : UserDao.java
with MIT License
from yocaning

// 添加用户
public void saveUser(UserBean user) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    session.save(user);
    ts.commit();
    session.close();
}

18 Source : UserDao.java
with MIT License
from yocaning

// 删除用户
public void deleteUser(short userid) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    UserBean user = findCurruser(userid);
    if (user != null)
        session.delete(user);
    ts.commit();
    session.close();
}

18 Source : RoleDao.java
with MIT License
from yocaning

// 删除角色
public void deleteRole(Integer roleid) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    RoleBean role = findCurrurole(roleid);
    if (role != null)
        session.delete(role);
    ts.commit();
    session.close();
}

18 Source : RoleDao.java
with MIT License
from yocaning

// 添加角色
public void saveRole(RoleBean role) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    session.save(role);
    ts.commit();
    session.close();
}

18 Source : RoleDao.java
with MIT License
from yocaning

// 修改角色
public void updateRole(RoleBean role) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    session.update(role);
    ts.commit();
    session.close();
}

18 Source : OrderDao.java
with MIT License
from yocaning

// 修改起点
public void updateorder(orderBean order) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    session.update(order);
    ts.commit();
    session.close();
}

18 Source : OrderDao.java
with MIT License
from yocaning

// 删除起点
public void deleteorder(Integer orderid) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    orderBean order = findCurrorder(orderid);
    if (order != null)
        session.delete(order);
    ts.commit();
    session.close();
}

18 Source : OrderDao.java
with MIT License
from yocaning

// //this.deleterolepower(powerid);
// Connection conn = UserUtil.getConnection();
// PreparedStatement ps = null ;
// ResultSet rs = null;
// String sql = "delete  t_order  where orderid =?";
// try {
// ps = conn.prepareStatement(sql);
// ps.setInt(1, orderid);
// ps.executeUpdate();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }finally{
// UserUtil.CloseAll(conn, ps, rs);
// }
// }
// 添加起点
public void saveorder(orderBean order) {
    Session session = hibernateUtil.getSession();
    Transaction ts = session.beginTransaction();
    session.save(order);
    ts.commit();
    session.close();
}

18 Source : HibernateTransactionManager.java
with MIT License
from Vip-Augus

@Override
protected void doCommit(DefaultTransactionStatus status) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction();
    Transaction hibTx = txObject.getSessionHolder().getTransaction();
    replacedert.state(hibTx != null, "No Hibernate transaction");
    if (status.isDebug()) {
        logger.debug("Committing Hibernate transaction on Session [" + txObject.getSessionHolder().getSession() + "]");
    }
    try {
        hibTx.commit();
    } catch (org.hibernate.TransactionException ex) {
        // replacedumably from commit call to the underlying JDBC connection
        throw new TransactionSystemException("Could not commit Hibernate transaction", ex);
    } catch (HibernateException ex) {
        // replacedumably failed to flush changes to database
        throw convertHibernateAccessException(ex);
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof HibernateException) {
            throw convertHibernateAccessException((HibernateException) ex.getCause());
        }
        throw ex;
    }
}

18 Source : AuditLogLocalDAORdbImpl.java
with Apache License 2.0
from VertaAI

public void saveAuditLogs(List<AuditLogLocalEnreplacedy> auditLogEnreplacedies) {
    try (Session session = modelDBHibernateUtil.getSessionFactory().openSession()) {
        Transaction transaction = session.beginTransaction();
        saveAuditLogs(session, auditLogEnreplacedies);
        transaction.commit();
        LOGGER.debug("Audit logged successfully");
    } catch (Exception ex) {
        if (ModelDBUtils.needToRetry(ex)) {
            saveAuditLogs(auditLogEnreplacedies);
        } else {
            throw ex;
        }
    }
}

18 Source : AbstractDAO.java
with Apache License 2.0
from V1toss

/**
 * Template method w/o return.
 * @param action action to do.
 */
private void persist(Action action) {
    Transaction transaction = null;
    try (Session session = HibernateUtil.getFactory().openSession()) {
        transaction = session.beginTransaction();
        action.execute(session);
        transaction.commit();
    } catch (HibernateException he) {
        LOG.error(he.getMessage(), he);
        if (transaction != null) {
            transaction.rollback();
        }
    }
}

18 Source : AbstractDAO.java
with Apache License 2.0
from V1toss

/**
 * Template method with list return.
 * @param action action to do.
 * @return list of objects.
 */
@SuppressWarnings("unchecked")
public List<T> persistGetAll(ActionGet action) {
    Transaction transaction = null;
    List<T> list = new ArrayList<>();
    try (Session session = HibernateUtil.getFactory().openSession()) {
        transaction = session.beginTransaction();
        list = action.executeGet(session);
        transaction.commit();
    } catch (HibernateException he) {
        LOG.error(he.getMessage(), he);
        if (transaction != null) {
            transaction.rollback();
        }
    }
    return list;
}

18 Source : DatabaseCtx.java
with MIT License
from ria-ee

/**
 * Commits the transaction.
 */
public void commitTransaction() {
    log.trace("commitTransaction({})", sessionFactoryName);
    Transaction tx = getSession().getTransaction();
    if (tx.isActive() && !tx.wasCommitted()) {
        tx.commit();
    }
}

18 Source : ErrorDaoImpl.java
with GNU Lesser General Public License v2.1
from phoenixctms

@Override
public void handleCreateTxn(Error error) throws Exception {
    // http://www.koders.com/java/fidDC3AD0DFC450E26BD45E4A8FA856716E422119F3.aspx?s=Closer
    Transaction transaction = this.getSession(true).beginTransaction();
    try {
        this.getSession().save(error);
        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    }
}

18 Source : AspDaoImpl.java
with GNU Lesser General Public License v2.1
from phoenixctms

@Override
public void handleRemoveTxn(Long aspId) throws Exception {
    Transaction transaction = this.getSession(true).beginTransaction();
    try {
        removeAsp(aspId);
        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    }
}

18 Source : AspDaoImpl.java
with GNU Lesser General Public License v2.1
from phoenixctms

@Override
public void handleRemoveTxn(Asp asp) throws Exception {
    Transaction transaction = this.getSession(true).beginTransaction();
    try {
        removeAsp(asp.getId());
        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    }
}

18 Source : HibernateStore.java
with Apache License 2.0
from peterarsentev

/**
 * Wrapper for transactions.
 * @param command actions.
 * @param <T> model type.
 * @return result of actions.
 */
private <T> T tx(final Function<Session, T> command) {
    final Session session = factory.openSession();
    final Transaction tx = session.beginTransaction();
    try {
        T rsl = command.apply(session);
        tx.commit();
        return rsl;
    } catch (final Exception e) {
        session.getTransaction().rollback();
        throw e;
    } finally {
        session.close();
    }
}

18 Source : HibernateUtil.java
with GNU General Public License v2.0
from openkm

/**
 * Commit transaction
 */
public static void commit(Transaction tx) {
    if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
        tx.commit();
    }
}

18 Source : AbstractHibernateMigration.java
with Apache License 2.0
from openequella

protected void runInTransaction(SessionFactory factory, HibernateCall call) throws Exception {
    Transaction trans = null;
    Session session = null;
    try {
        session = factory.openSession();
        trans = session.beginTransaction();
        call.run(session);
        trans.commit();
    } catch (Exception t) {
        if (trans != null) {
            trans.rollback();
        }
        Throwables.propagate(t);
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

18 Source : SessionBox.java
with MIT License
from oimchat

public <T> void save(T t) {
    Session session = this.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    try {
        session.save(t);
        transaction.commit();
    } catch (Exception e) {
        e.printStackTrace();
        transaction.rollback();
    }
}

18 Source : Car_Details_Tester.java
with BSD 3-Clause "New" or "Revised" License
from ohbus

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Configuration cfg = new Configuration().configure("myconfig.cfg.xml");
    SessionFactory sf = cfg.buildSessionFactory();
    Session session = sf.openSession();
    Transaction transaction = session.beginTransaction();
    Car_Details cd = new Car_Details();
    session.save(cd);
    transaction.commit();
    System.out.println("Record Inserted!");
    session.close();
}

18 Source : ConceptDao.java
with Apache License 2.0
from nhsconnect

public void commitTransaction(Transaction tx) {
    tx.commit();
}

18 Source : HibernateTest.java
with Apache License 2.0
from newrelic

@Trace(dispatcher = true)
private void _refresh1() {
    Transaction transaction = session.beginTransaction();
    Serializable id = savePlayer();
    transaction.commit();
    Object player = session.get(Player.clreplaced, id);
    session.refresh(player);
}

18 Source : HibernateTest.java
with Apache License 2.0
from newrelic

@Trace(dispatcher = true)
private void _saveOrUpdate1() {
    Player dude = new Player();
    dude.setId(nextId++);
    Transaction transaction = session.beginTransaction();
    session.saveOrUpdate(dude);
    transaction.commit();
}

18 Source : HibernateStatsTest.java
with Apache License 2.0
from newrelic

@Trace(dispatcher = true)
@Test
public void transactions() {
    float count = 10;
    for (int i = 0; i < count; i++) {
        Transaction tx = session.beginTransaction();
        tx.commit();
    }
    runSamplers();
    Stats stats = getTransactionStats().getStats("HibernateStatistics/transactions");
    replacedertEquals(count, stats.getTotal(), 0);
}

18 Source : BinContentDAOHibImpl.java
with GNU Affero General Public License v3.0
from KnowageLabs

/*
	 * (non-Javadoc)
	 *
	 * @see it.eng.spagobi.commons.dao.IBinContentDAO#getBinContent(java.lang.Integer)
	 */
@Override
public byte[] getBinContent(Integer binId) throws HibernateException {
    logger.debug("IN");
    if (binId != null)
        logger.debug("binId=" + binId.toString());
    byte[] content = new byte[0];
    Session aSession = null;
    Transaction tx = null;
    try {
        aSession = getSession();
        tx = aSession.beginTransaction();
        SbiBinContents hibBinCont = (SbiBinContents) aSession.load(SbiBinContents.clreplaced, binId);
        content = hibBinCont.getContent();
        tx.commit();
    } catch (HibernateException he) {
        logger.error("HibernateException", he);
        if (tx != null)
            tx.rollback();
        throw new HibernateException(he.getLocalizedMessage(), he);
    } finally {
        if (aSession != null) {
            if (aSession.isOpen())
                aSession.close();
        }
        logger.debug("OUT");
    }
    return content;
}

18 Source : DataAccessServiceImpl.java
with Apache License 2.0
from jveverka

@Override
public void saveUserData(UserData userData) {
    Transaction transaction = null;
    try (Session session = this.sessionFactory.openSession()) {
        transaction = session.beginTransaction();
        LOG.info("save user data, TX started");
        session.save(userData);
        transaction.commit();
        LOG.info("save user data, TX committed");
    } catch (Exception e) {
        LOG.error("Error: ", e);
        if (transaction != null) {
            LOG.info("user data rollback, TX rollback");
            transaction.rollback();
        }
    }
}

18 Source : DataAccessServiceImpl.java
with Apache License 2.0
from jveverka

@Override
public void deleteUserData(long id) {
    Transaction transaction = null;
    try (Session session = this.sessionFactory.openSession()) {
        transaction = session.beginTransaction();
        LOG.info("delete user data id={}, TX started", id);
        // Delete a transient  object
        UserData userData = new UserData(id);
        session.delete(userData);
        transaction.commit();
        LOG.info("delete user data id={}, TX committed", id);
    } catch (Exception e) {
        LOG.error("Error: ", e);
        if (transaction != null) {
            LOG.info("user data rollback, TX rollback");
            transaction.rollback();
        }
    }
}

18 Source : OrderRepositoryDefault.java
with GNU General Public License v3.0
from ivan909020

@Override
public void save(Order order) {
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    session.save(order);
    transaction.commit();
    session.close();
}

18 Source : TestUtil.java
with Apache License 2.0
from IBM

private static void initializeDatabase(Database database) {
    Session session = database.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
    getPersons().forEach(session::persist);
    tx.commit();
    session.close();
}

18 Source : OneToManyTest.java
with Apache License 2.0
from huifer

/**
 * 联系人2 改成客户2
 * 提交多次sql
 * 一方放弃外键维护权
 */
@Test
public void demo6() {
    demo1();
    Session session = HibernateUtils.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    LinkMan linkMan = session.get(LinkMan.clreplaced, 2L);
    Customer customer = session.get(Customer.clreplaced, 2L);
    linkMan.setCustomer(customer);
    customer.getLinkMans().add(linkMan);
    transaction.commit();
}

18 Source : OneToManyTest.java
with Apache License 2.0
from huifer

/**
 * 级联保存
 * * 保存联系人级联客户
 * * 联系人 ->客户
 * * 联系人是主体,配置 cascade
 */
@Test
public void demo3() {
    Session session = HibernateUtils.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    Customer customer = new Customer();
    customer.setCust_name("级联保存客户2");
    LinkMan linkMan = new LinkMan();
    linkMan.setLkm_name("级联联系人2");
    customer.getLinkMans().add(linkMan);
    linkMan.setCustomer(customer);
    session.save(linkMan);
    transaction.commit();
}

18 Source : OneToManyTest.java
with Apache License 2.0
from huifer

@Test
public void demo1() {
    Session session = HibernateUtils.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    // 创建两个客户
    Customer customer1 = new Customer();
    customer1.setCust_name("客户1");
    Customer customer2 = new Customer();
    customer2.setCust_name("客户2");
    // 创建三个联系人
    LinkMan linkMan1 = new LinkMan();
    linkMan1.setLkm_name("联系人1");
    LinkMan linkMan2 = new LinkMan();
    linkMan2.setLkm_name("联系人2");
    LinkMan linkMan3 = new LinkMan();
    linkMan3.setLkm_name("联系人3");
    // 设置关系:
    linkMan1.setCustomer(customer1);
    linkMan2.setCustomer(customer1);
    linkMan3.setCustomer(customer2);
    customer1.getLinkMans().add(linkMan1);
    customer1.getLinkMans().add(linkMan2);
    customer2.getLinkMans().add(linkMan3);
    // 保存数据:
    session.save(linkMan1);
    session.save(linkMan2);
    session.save(linkMan3);
    session.save(customer1);
    session.save(customer2);
    transaction.commit();
}

18 Source : OneToManyTest.java
with Apache License 2.0
from huifer

/**
 * cascade & inverse 区别
 * cascade 关联对象操作
 * inverse 外键操作
 */
@Test
public void demo7() {
    Session session = HibernateUtils.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    Customer customer = new Customer();
    customer.setCust_name("级联保存客户1");
    LinkMan linkMan = new LinkMan();
    linkMan.setLkm_name("级联联系人1");
    customer.getLinkMans().add(linkMan);
    linkMan.setCustomer(customer);
    // <set name="linkMans" cascade="save-update,delete" inverse="true">
    // 两个实体都会保存 但是没有外键
    session.save(customer);
    transaction.commit();
}

18 Source : OneToManyTest.java
with Apache License 2.0
from huifer

/**
 * 对象导航
 * 双方都配置 cascade
 */
@Test
public void demo4() {
    Session session = HibernateUtils.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    Customer customer = new Customer();
    customer.setCust_name("cust01");
    LinkMan linkMan1 = new LinkMan();
    linkMan1.setLkm_name("LM1");
    LinkMan linkMan2 = new LinkMan();
    linkMan2.setLkm_name("LM2");
    LinkMan linkMan3 = new LinkMan();
    linkMan3.setLkm_name("LM3");
    linkMan1.setCustomer(customer);
    customer.getLinkMans().add(linkMan2);
    customer.getLinkMans().add(linkMan3);
    // 双方都设置了cascade
    // session.save(linkMan1); // 发送几条insert语句  4条
    // session.save(customer); // 发送几条insert语句  3条
    // session.save(linkMan2); // 发送几条insert语句  1条
    transaction.commit();
}

18 Source : OneToManyTest.java
with Apache License 2.0
from huifer

/**
 * 级联删除
 */
@Test
public void demo5() {
    demo1();
    Session session = HibernateUtils.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    Customer customer = session.get(Customer.clreplaced, 1L);
    session.delete(customer);
    transaction.commit();
}

18 Source : OneToManyTest.java
with Apache License 2.0
from huifer

/**
 * 级联保存
 * * 保存客户级联联系人
 * * 客户 -> 联系人
 * *客户是主体,配置 cascade
 */
@Test
public void demo2() {
    Session session = HibernateUtils.getCurrentSession();
    Transaction transaction = session.beginTransaction();
    Customer customer = new Customer();
    customer.setCust_name("级联保存客户1");
    LinkMan linkMan = new LinkMan();
    linkMan.setLkm_name("级联联系人1");
    customer.getLinkMans().add(linkMan);
    linkMan.setCustomer(customer);
    session.save(customer);
    transaction.commit();
}

18 Source : ManyToManyTest.java
with Apache License 2.0
from huifer

/**
 * 给用户选角色
 */
@Test
public void demo2() {
    demo1();
    Session session = HibernateUtils.getCurrentSession();
    Transaction tx = session.beginTransaction();
    // 给1号用户多选2号角色
    // 查询1号用户
    User user = session.get(User.clreplaced, 1L);
    // 查询2号角色
    Role role = session.get(Role.clreplaced, 2L);
    user.getRoles().add(role);
    tx.commit();
}

18 Source : ManyToManyTest.java
with Apache License 2.0
from huifer

@Test
public /**
 * 保存多条记录:保存多个用户和角色
 */
void demo1() {
    Session session = HibernateUtils.getCurrentSession();
    Transaction tx = session.beginTransaction();
    // 创建2个用户
    User user1 = new User();
    user1.setUser_name("用户1");
    User user2 = new User();
    user2.setUser_name("用户2");
    // 创建3个角色
    Role role1 = new Role();
    role1.setRole_name("角色A");
    Role role2 = new Role();
    role2.setRole_name("角色B");
    Role role3 = new Role();
    role3.setRole_name("角色C");
    // 设置双向的关联关系:
    user1.getRoles().add(role1);
    user1.getRoles().add(role1);
    user1.getRoles().add(role2);
    user2.getRoles().add(role2);
    user2.getRoles().add(role3);
    role1.getUsers().add(user1);
    role2.getUsers().add(user1);
    role2.getUsers().add(user2);
    role3.getUsers().add(user2);
    // 保存操作:多对多建立了双向的关系必须有一方放弃外键维护。
    // 一般是被动方放弃外键维护权。
    session.save(user1);
    session.save(user2);
    session.save(role1);
    session.save(role2);
    session.save(role3);
    tx.commit();
}

18 Source : ManyToManyTest.java
with Apache License 2.0
from huifer

/**
 * 给用户改选角色
 */
@Test
public void demo3() {
    demo1();
    Session session = HibernateUtils.getCurrentSession();
    Transaction tx = session.beginTransaction();
    // 给2号用户将原有的2号角色改为3号角色
    // 查询2号用户
    User user = session.get(User.clreplaced, 2L);
    // 查询2号角色
    Role role2 = session.get(Role.clreplaced, 2L);
    Role role3 = session.get(Role.clreplaced, 3L);
    user.getRoles().remove(role2);
    user.getRoles().add(role3);
    tx.commit();
}

18 Source : BuiltinTypeMappingTest.java
with GNU Lesser General Public License v2.1
from hibernate

@After
public void removeTestData() {
    OgmSession session = openSession();
    Transaction transaction = session.beginTransaction();
    session.delete(session.get(Bookmark.clreplaced, bookmarkId));
    transaction.commit();
    session.close();
}

18 Source : Hib.java
with Apache License 2.0
from guzhigang001

/**
 * 简化事务操作的一个工具方法
 *
 * @param query
 */
public static void queryOnOnly(QueryOnOnly query) {
    // 重新开启一个Session 避免提示重复使用相同的Session
    Session session = sessionFactory().openSession();
    // 开启一个事务
    final Transaction transaction = session.beginTransaction();
    try {
        // 调用传进了来的接口,并调用接口中的方法 把Session传进方法中
        // 以便提供给调用者利用Session去进行数据库的操作
        query.query(session);
        // 提交事务
        transaction.commit();
    } catch (Exception e) {
        e.printStackTrace();
        try {
            // 保存失败的情况下进行事务回滚
            transaction.rollback();
        } catch (RuntimeException e1) {
            e1.printStackTrace();
        }
    } finally {
        // 关闭session
        session.close();
    }
}

18 Source : Hib.java
with Apache License 2.0
from guzhigang001

/**
 * 简化事务操作的一个工具方法
 * 有返回值
 *
 * @param query 用于接收session
 * @param <T>   表示的实体
 * @return
 */
public static <T> T query(Query<T> query) {
    // 重新开启一个Session 避免提示重复使用相同的Session
    Session session = sessionFactory().openSession();
    // 开启一个事务
    final Transaction transaction = session.beginTransaction();
    T t = null;
    try {
        // 调用传进了来的接口,并调用接口中的方法 把Session传进方法中
        // 以便提供给调用者利用Session去进行数据库的操作
        t = query.query(session);
        // 提交事务
        transaction.commit();
    } catch (Exception e) {
        e.printStackTrace();
        try {
            // 保存失败的情况下进行事务回滚
            transaction.rollback();
        } catch (RuntimeException e1) {
            e1.printStackTrace();
        }
    } finally {
        // 关闭session
        session.close();
    }
    return t;
}

18 Source : HibernateFlushProvider.java
with Apache License 2.0
from exactpro

@Override
public void flush(List<T> objects) throws Exception {
    Session session = null;
    Transaction tx = null;
    try {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        for (T object : objects) {
            session.save(object);
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

18 Source : DatabaseUtils.java
with MIT License
from ConnectedPlacesCatapult

public static void clearAllData() {
    // We need to do this to clear the data from the session
    HibernateUtil.restart();
    HibernateUtil.withSession(session -> {
        Transaction transaction = session.beginTransaction();
        session.createNativeQuery("TRUNCATE timed_value, fixed_value, attribute, subject, database_journal").executeUpdate();
        session.createNativeQuery("DELETE FROM subject_type WHERE label NOT IN ('unknown', 'poi')").executeUpdate();
        session.createNativeQuery("DELETE FROM provider WHERE label NOT IN ('default_provider_label')").executeUpdate();
        transaction.commit();
    });
}

See More Examples