事务_单个数据库_多个数据库(JTATransaction)_session context和事务边界(大多用于WEB)_悲观锁与乐观锁


事务_单个数据库_多个数据库(JTATransaction)_session context和事务边界(大多用于WEB)_悲观锁与乐观锁

事务_单个数据库_多个数据库( JTATransaction)

JDBCTransaction
单个数据库(一个SesisonFactory对应一个数据库),由JDBC实现。
Session session = null;
Transaction tx =null;
try {
session = sessionFactory.openSession();
tx = session.beginTransaction();
//process
tx.commit();
} catch(HibernateException e){
if(tx != null)tx.rollback();throw e;
}finally {
if (session != null)session.close();
}
connection.setAutoCommit(false);
connection.commit();conn.rollback();
l




JTATransaction
可以简单的理解成跨数据库的事物,由应用JTA 容器实现;
使用JTATransaction需要配置hibernate.transaction.factory_class参数,
该参数缺省值是org.hibernate.transaction. JDBCTransactionFactory,

当使用JTATransaction时需要将该参数改成org.hibernate.transaction.JTATransactionFactory,
并配置jta.UserTransaction参数JNDI名(Hibernate在启动JTATransaction时要用该值到JNDI的上下文Context中去找javax.transaction.UserTransaction)。

javax.transaction.UserTransactin tx = context.lookup(“jndiName”);
try{
tx.begin();
//多个数据库的session操作;
//session1….
//session2….
tx.commit();
}catch(Exception e){
tx.rollback(); throw e;
}



session context和事务边界(大多用于WEB)
用current_session_context_class属性来定义context(用sessionFactory.getCurrentSession()来获得session)
其值为:
1.thread:ThreadLocal来管理Session实现多个操作共享一个Session,
避免反复获取Session,并控制事务边界,
此时session不能调用close当commit或rollback的时候session会自动关闭(connection.release_mode:after_transaction)。
Open session in view:在生成(渲染)页面时保持 session打开。

2.jta:由JTA事务管理器来管理事务(connection.release_mode:after_statement)。


(模拟)_ThreadLocal来管理Session实现多个操作共享一个Session(模拟)

1.HibernateUtil工具类,添加 getThreadLocalSession(),closeSession()
	public static Session getThreadLocalSession(){
		Session session=(Session)threadLocalSession.get();
		if(session==null){
			session=getSession();
			threadLocalSession.set(session);
		}
		return session;
	}
	public static void closeSession(){
		Session session=(Session)threadLocalSession.get();
		if(session!=null){
			session.close();
			threadLocalSession.set(null);
		}
	}

2.servlet 过滤器 (实现接口Filter)
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getThreadLocalSession();
			tx = session.beginTransaction();
			filterChain.doFilter(request, response);
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			HibernateUtil.closeSession();
		}
	}


3.UserDAO.java
package com.dwt1220;

public class UserDao {
	public void addUser(User user){
		HibernateUtil.getThreadLocalSession().save(user);
	}
}

悲观锁与乐观锁

1、悲观锁由数据库来实现;

2、乐观锁hibernate用version和timestamp来实现
1、为类添加version   or timestamp 字段;(timestamp必须是Date类型,version随便)
2、配置文件设置。在id标签后添加 version or timestamp 字段
User.java
package com.dwt1220;

import java.util.Date;

public class User {

	private int id;
	private Name name;
	private Date birthday;
	private int version;
//	private Date timestamp;

	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

//	public Date getTimestamp() {
//		return timestamp;
//	}
//
//	public void setTimestamp(Date timestamp) {
//		this.timestamp = timestamp;
//	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public Name getName() {
		return name;
	}

	public void setName(Name name) {
		this.name = name;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}

User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.dwt1220">
<!-- 	<class name="User" table"user"> table 属性可选(类对应的表名),如果表名和字段名是数据库的关节字,可以加''-->
	<class name="User">
		<id name="id">
			<generator class="native"/>
		</id>
		<!-- 必须放在id后面 -->
		<version name="version"/>
		<!-- or 
		<timestamp name="timestamp"/>
		 一般使用 version方式, timestamp 不够精确
		 -->
		<component name="name">
			<property name="firstName" column="first_name"></property>
			<property name="lastName" column="last_name"></property>
		</component>
		<property name="birthday"/>
	
	</class>
	
</hibernate-mapping>

Test.java
package com.dwt1220;


import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

	public static void main(String[] args) {
		
		Name name=new Name();
		name.setFirstName("firstName");
		name.setLastName("lastName");
	
		User user=new User();
		user.setBirthday(new Date());
		user.setName(name);
		
		add(user);
		
		update(1);
		System.out.println("end");
		
		query(1);
	}


	static void update(int id) {
		Session session1 = null;
		Transaction tx1 = null;
		
		Session session2 = null;
		Transaction tx2 = null;
		try {
			session1 = HibernateUtil.getSession();
			tx1 = session1.beginTransaction();
			User user1=(User)session1.get(User.class,id);
			
			session2 = HibernateUtil.getSession();
			tx2 = session1.beginTransaction();			
			User user2=(User)session2.get(User.class, id);

			user1.getName().setFirstName("new1 fistName");
			user2.getName().setFirstName("new2 fistName");

			tx2.commit();
			tx1.commit();//此处应版本号错误,报错。
		} finally {
			if (session1 != null&&session2!=null) {
				session1.close();
				session2.close();
			}
		}
	}
	
	static void query(int id) {
		Session session = null;
		User user=null;
		try {
			session = HibernateUtil.getSession();
			user=(User)session.get(User.class, id);
			System.out.println("User.firstname:"+user.getName().getFirstName());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
	
	static void add(Object object) {
		Session session = null;
		Transaction tx = null;
		try {
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			session.save(object);
			tx.commit();
			// 不catch,出错会自动回滚
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

}



你可能感兴趣的:(Date,数据库,Web,session,user,null)