博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hibernate的持久化上下文的事务API
阅读量:4178 次
发布时间:2019-05-26

本文共 1410 字,大约阅读时间需要 4 分钟。

Hibernate 的持久化上下文提供了一系列的事务API,这些事务API,只是为了分离上层应用与底层数据库,便于将来可能的数据库迁移。Hibernate本身没有提供任何新的事务特性。

使用Hibernate的API的步骤如下:

  1. 通过Session获取org.hibernate.Transaction对象;
  2. 通过org.hibernate.Transaction对象执行事务操作。

Hibernate的API提供如下事务操作:

  • begin(), commit(), rollback()
  • markRollbackOnly()
  • getTimeout(), setTimeout()
  • registerSynchronization()
  • getStatus()

Hibernate使用JDBC事务或JTA事务(BMT)示例如下:

Session session = sessionFactory.openSession();try {    // calls Connection#setAutoCommit( false ) to    // signal start of transaction    session.getTransaction().begin();    session.createQuery( "UPDATE customer set NAME = 'Sir. '||NAME" )            .executeUpdate();    // calls Connection#commit(), if an error    // happens we attempt a rollback    session.getTransaction().commit();}catch ( Exception e ) {    // we may need to rollback depending on    // where the exception happened    if ( session.getTransaction().getStatus() == TransactionStatus.ACTIVE            || session.getTransaction().getStatus() == TransactionStatus.MARKED_ROLLBACK ) {        session.getTransaction().rollback();    }    // handle the underlying error}finally {    session.close();}
Hibernate使用JTA事务(CMT)示例如下:

Session session = sessionFactory.openSession();try {    Number customerCount = (Number) session.createQuery( "select count(c) from Customer c" ).uniqueResult();}catch ( Exception e ) {    // handle the underlying error}finally {    session.close();}

转载地址:http://milai.baihongyu.com/

你可能感兴趣的文章
linux中的run-level何解?
查看>>
Linux内核编译详解(转自linuxSir)
查看>>
实模式,保护模式与V86模式
查看>>
628. Maximum Product of Three Numbers(排序)
查看>>
Linux内核-------同步机制(一)
查看>>
485. Max Consecutive Ones(数组)
查看>>
287. Find the Duplicate Number(数组)
查看>>
Linux内核-------同步机制(二)
查看>>
面试题31-------连续子数组的最大和(数组)
查看>>
epoll 实现Chat
查看>>
21. Merge Two Sorted Lists(链表)
查看>>
2. Add Two Numbers(链表)
查看>>
637. Average of Levels in Binary Tree(Tree)
查看>>
226. Invert Binary Tree(Tree)
查看>>
328. Odd Even Linked List(链表)
查看>>
617. Merge Two Binary Trees(Tree)
查看>>
700. Search in a Binary Search Tree(Tree)
查看>>
515. Find Largest Value in Each Tree Row(Tree)
查看>>
897. Increasing Order Search Tree(Tree)
查看>>
199. Binary Tree Right Side View(Tree)
查看>>