Home Database Mysql Tutorial Eclipse开发Hibernate应用程序_MySQL

Eclipse开发Hibernate应用程序_MySQL

Jun 01, 2016 pm 02:11 PM
hibernate transaction app develop

HibernateEclipse

  
  Hibernate是对JDBC的轻量级对象封装,Hibernate本身是不具备Transaction处理功能的,Hibernate的Transaction实际上是底层的JDBC Transaction的封装,或者是JTA Transaction的封装,下面我们详细的分析:

  Hibernate可以配置为JDBCTransaction或者是JTATransaction,这取决于你在hibernate.properties中的配置:

  #hibernate.transaction.factory_class
  net.sf.hibernate.transaction.JTATransactionFactory
  #hibernate.transaction.factory_class
  net.sf.hibernate.transaction.JDBCTransactionFactory

  如果你什么都不配置,默认情况下使用JDBCTransaction,如果你配置为:

  hibernate.transaction.factory_class
  net.sf.hibernate.transaction.JTATransactionFactory

  将使用JTATransaction,不管你准备让Hibernate使用JDBCTransaction,还是JTATransaction,我的忠告就是什么都不配,将让它保持默认状态,如下:

  #hibernate.transaction.factory_class
  net.sf.hibernate.transaction.JTATransactionFactory
  #hibernate.transaction.factory_class
  net.sf.hibernate.transaction.JDBCTransactionFactory

  在下面的分析中我会给出原因。

  一、JDBC Transaction

  看看使用JDBC Transaction的时候我们的代码例子:

  Session session = sf.openSession();
  Transaction tx = session.beginTransactioin();
  ...
  session.flush();
  tx.commit();
  session.close();

  这是默认的情况,当你在代码中使用Hibernate的Transaction的时候实际上就是JDBCTransaction。那么JDBCTransaction究竟是什么东西呢?来看看源代码就清楚了:

  Hibernate2.0.3源代码中的类

  net.sf.hibernate.transaction.JDBCTransaction:

  public void begin() throws HibernateException {
  ...
  if (toggleAutoCommit) session.connection().setAutoCommit(false);
  ...
  }

  这是启动Transaction的方法,看到 connection().setAutoCommit(false) 了吗?是不是很熟悉?

  再来看

  public void commit() throws HibernateException {
  ...
  try {
  if ( session.getFlushMode()!=FlushMode.NEVER ) session.flush();
  try {
  session.connection().commit();
  committed = true;
  }
  ...
  toggleAutoCommit();
  }

  这是提交方法,看到connection().commit() 了吗?下面就不用我多说了,这个类代码非常简单易懂,通过阅读使我们明白Hibernate的Transaction都在干了些什么?我现在把用Hibernate写的例子翻译成JDBC,大家就一目了然了:

  Connection conn = ...;   conn.setAutoCommit(false);   ...   conn.commit();   conn.setAutoCommit(true);
  conn.close();
  看明白了吧,Hibernate的JDBCTransaction根本就是conn.commit而已,根本毫无神秘可言,只不过在Hibernate中,Session打开的时候,就会自动conn.setAutoCommit(false),不像一般的JDBC,默认都是true,所以你最后不写commit也没有关系,由于Hibernate已经把AutoCommit给关掉了,所以用Hibernate的时候,你在程序中不写Transaction的话,数据库根本就没有反应。

  二、JTATransaction

  如果你在EJB中使用Hibernate,或者准备用JTA来管理跨Session的长事务,那么就需要使用JTATransaction,先看一个例子:

  javax.transaction.UserTransaction tx = new
  InitialContext().lookup("javax.transaction.UserTransaction");
  Session s1 = sf.openSession();
  ...
  s1.flush();
  s1.close();
  ...
  Session s2 = sf.openSession();
  ...
  s2.flush();
  s2.close();
  tx.commit();

  这是标准的使用JTA的代码片断,Transaction是跨Session的,它的生命周期比Session要长。如果你在EJB中使用Hibernate,那么是最简单不过的了,你什么Transaction代码统统都不要写了,直接在EJB的部署描述符上配置某某方法是否使用事务就可以了。

  现在我们来分析一下JTATransaction的源代码, net.sf.hibernate.transaction.JTATransaction:

  public void begin(InitialContext context, ...
  ...
  ut = (UserTransaction) context.lookup(utName);
  ...

  看清楚了吗? 和我上面写的代码 tx = new Initial Context?().lookup("javax.transaction.UserTransaction"); 是不是完全一样?

  public void commit() ...
  ...
  if (newTransaction) ut.commit();
  ...

  JTATransaction的控制稍微复杂,不过仍然可以很清楚的看出来Hibernate是如何封装JTA的Transaction代码的。

  但是你现在是否看到了什么问题? 仔细想一下,Hibernate Transaction是从Session中获得的,tx = session.beginTransaction(),最后要先提交tx,然后再session.close,这完全符合JDBC的Transaction的操作顺序,但是这个顺序是和JTA的Transactioin操作顺序彻底矛盾的!!! JTA是先启动Transaction,然后启动Session,关闭Session,最后提交Transaction,因此当你使用JTA的Transaction的时候,那么就千万不要使用Hibernate的Transaction,而是应该像我上面的JTA的代码片断那样使用才行。

  总结:

  1、在JDBC上使用Hibernate 必须写上Hibernate Transaction代码,否则数据库没有反应。此时Hibernate的Transaction就是Connection.commit而已

  2、在JTA上使用Hibernate 写JTA的Transaction代码,不要写Hibernate的Transaction代码,否则程序会报错

  3、在EJB上使用Hibernate 什么Transactioin代码都不要写,在EJB的部署描述符里面配置

  |---CMT(Container Managed Transaction)
  |
  |---BMT(Bean Managed Transaction)
  |
  |----JDBC Transaction
  |
  |----JTA Transaction

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unable to save changes to Photos app error in Windows 11 Unable to save changes to Photos app error in Windows 11 Mar 04, 2024 am 09:34 AM

If you encounter the Unable to save changes error while using the Photos app for image editing in Windows 11, this article will provide you with solutions. Unable to save changes. An error occurred while saving. Please try again later. This problem usually occurs due to incorrect permission settings, file corruption, or system failure. So, we’ve done some deep research and compiled some of the most effective troubleshooting steps to help you resolve this issue and ensure you can continue to use the Microsoft Photos app seamlessly on your Windows 11 device. Fix Unable to Save Changes to Photos App Error in Windows 11 Many users have been talking about Microsoft Photos app error on different forums

MS Paint not working properly in Windows 11 MS Paint not working properly in Windows 11 Mar 09, 2024 am 09:52 AM

Microsoft Paint not working in Windows 11/10? Well, this seems to be a common problem and we have some great solutions to fix it. Users have been complaining that when trying to use MSPaint, it doesn't work or open. Scrollbars in the app don't work, paste icons don't show up, crashes, etc. Luckily, we've collected some of the most effective troubleshooting methods to help you resolve issues with Microsoft Paint app. Why doesn't Microsoft Paint work? Some possible reasons why MSPaint is not working on Windows 11/10 PC are as follows: The security identifier is corrupted. hung system

How to connect Apple Vision Pro to PC How to connect Apple Vision Pro to PC Apr 08, 2024 pm 09:01 PM

The Apple Vision Pro headset is not natively compatible with computers, so you must configure it to connect to a Windows computer. Since its launch, Apple Vision Pro has been a hit, and with its cutting-edge features and extensive operability, it's easy to see why. Although you can make some adjustments to it to suit your PC, and its functionality depends heavily on AppleOS, so its functionality will be limited. How do I connect AppleVisionPro to my computer? 1. Verify system requirements You need the latest version of Windows 11 (Custom PCs and Surface devices are not supported) Support 64-bit 2GHZ or faster fast processor High-performance GPU, most

Shazam app not working in iPhone: Fix Shazam app not working in iPhone: Fix Jun 08, 2024 pm 12:36 PM

Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Move photos from old Photos to the new Photos app in Windows 11 Move photos from old Photos to the new Photos app in Windows 11 Mar 10, 2024 am 09:37 AM

This article will guide you on how to migrate photos from Photos Legacy to the new Photos app in Windows 11. Microsoft has introduced a revamped Photos app in Windows 11, giving users a simpler and more feature-rich experience. The new Photos app sorts photos differently than the past PhotosLegacy app. It organizes photos into folders like other Windows files instead of creating albums. However, users still using the Photos Legacy app can easily migrate their photos to the new version of Microsoft Photos. What is Phot

Why does 0xc0000142 error code appear? Why does 0xc0000142 error code appear? Feb 25, 2024 am 11:15 AM

0xc0000142 refers to the error code in Windows systems, and it is usually related to the problem of a program or application not starting or running properly. When a user tries to open a program, the system displays the error message "0xc0000142" and the program cannot continue to run. So, why does the 0xc0000142 error occur? There are many reasons for this error code, here are some common causes and solutions. Corrupted configuration files: The configuration files of some programs may be corrupted, causing

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

See all articles