纯Hibernate使用-不用spring事务管理

     最近一直在做系统测试,检验功能,测试bug。发现一直都是用spring来管理配置hibernate依赖注入,来管理Hibernate事务。但是有的程序需要手动Main函数启动,而采用spring加载的话,就会触发很多类,影响性能,还有当spring里面写了触发器后,那么随着你的main函数运行,你的触发器也得到了启动,那么这个会造成多个进程开启了触发器。

    当离开了spring管理时,发现Hibernate居然不知道怎么调用了,参考了网上一些大牛的文章,自己动手实现了,无需spring管理来进行Hibernate调用。

    直接上代码:1.工具类,2.xml配置文件,3.实体类,注释方式  4.测试功能类

package com.t.common.hibernate;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public final class HibernateUtil {
	
	private static SessionFactory sessionFactory;
	private static ThreadLocal session = new ThreadLocal();
	
	public HibernateUtil(){
		
	}
	static {
		Configuration cfg = new Configuration();
		cfg.configure("hibernate.common.xml");
		sessionFactory = cfg.buildSessionFactory();
	}
	
	public static Session getThreadLocalSession(){
		Session s = (Session) session.get();
		if(s==null){
			s=getSession();
			session.set(s);
		}
		return s;
	}
	public static void closeSession(){
		Session s = (Session)session.get();
		if(s!=null){
			s.close();
			session.set(null);
		}
	}
	public static SessionFactory getSessionFactory(){
		return sessionFactory;
	}
	public static Session getSession(){
		return sessionFactory.openSession();
	}
	//增删改查
	//当需要事务一致性的时候,需要回滚,比如商品系统
	/*
	 * public static void add(Object entity){
		Session s =null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(entity);
			tx.commit();
		} catch (HibernateException e) {  
            if(tx != null){  
                tx.rollback();  
            }  
            throw e;  
        }finally {
			if(s!=null){
				s.close();
			}
		}
	}
	 */
	public static void add(Object entity){
		Session s =null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.save(entity);
			tx.commit();
		} finally {
			if(s!=null){
				s.close();
			}
		}
	}
	public static void delete(Object entity){
		Session s =null;
		Transaction tx = null;
		try {
			s = HibernateUtil.getSession();
			tx = s.beginTransaction();
			s.delete(entity);
			tx.commit();
		} finally {
			if(s!=null){
				s.close();
			}
		}
	}
	public static Object get(Class clazz, Serializable id){
		Session s =null;
		try {
			s = HibernateUtil.getSession();
			Object obj = s.get(clazz, id);
			return obj;
		} finally {
			if(s!=null){
				s.close();
			}
		}
	}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
	<property name="hibernate.bytecode.use_reflection_optimizer">
		false
	</property>
	<property name="hibernate.connection.driver_class">
		oracle.jdbc.driver.OracleDriver
	</property>
	<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
	<property name="connection.username">baike</property>
	<property name="connection.password">baike</property>
	<property name="hibernate.dialect">
		org.hibernate.dialect.Oracle10gDialect
	</property>
	<property name="hibernate.search.autoregister_listeners">
		false
	</property>
	<property name="hibernate.show_sql">true</property>
	
	<!-- 映射类 -->
	<mapping class="com.t.common.hibernate.BaikeUser"/>
	
</session-factory>
</hibernate-configuration>
package com.t.common.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;


@Entity
@Table(name="T_USER")
public class BaikeUser {
	
	private Long id ; 
	private String username;
	private String password;
	
	@Id
	@SequenceGenerator(name="generator",allocationSize=1,initialValue=1,sequenceName="SEQ_USER_ID")
	@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="generator")
	@Column(name="ID")
	public Long getId() {
		return id;
	}
	@Column(name="username")
	public String getUsername() {
		return username;
	}
	@Column(name="password")
	public String getPassword() {
		return password;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}
package com.t.common.hibernate;

public class TestUSer {
	public static void main(String[] args) {
		
		BaikeUser user = new BaikeUser();
		user.setId(1L);
		user.setUsername("cjp1989");
		user.setPassword("12345");
		HibernateUtil.add(user);
	}
}

   1.注意事项:xml配置文件可以自定义的,但是<session-factory> 单独使用时,没有name属性

猜你喜欢

转载自cjp1989.iteye.com/blog/1915694