`
1140566087
  • 浏览: 548780 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
博客专栏
2c4ae07c-10c2-3bb0-a106-d91fe0a10f37
c/c++ 入门笔记
浏览量:18108
3161ba8d-c410-3ef9-871c-3e48524c5263
Android 学习笔记
浏览量:309927
Group-logo
J2ME 基础学习课程集
浏览量:18086
A98a97d4-eb03-3faf-af96-c7c28f709feb
Spring 学习过程记录...
浏览量:17223
社区版块
存档分类
最新评论

Hibernate 连接数据库的方法

阅读更多
初级,最笨重的方法:

package com.svse.dao;

import java.util.ArrayList;
import java.util.List;

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

import com.svse.entity.TDept;

//部门数据处理
public class DeptDao_1 {
	
	//全查询 , 
	public List getAll(){
		List ar = new ArrayList();
		//1、加载配置文件,连接数据库
		Configuration config = new Configuration().configure();
		//2、得到数据映射的工具:SessionFactory;
		SessionFactory sessionFactory = config.buildSessionFactory();
		//3、得到动作处理工具Session,执行相应的动作;
		Session session = sessionFactory.openSession();
		
		//4、使用Session工具执行动作;
		ar = session.createQuery("FROM TDept").list();
		
		//5、关闭工具
		session.close();
		return ar;
	}
	
	//查询一个
	public TDept getOne(int p_id){
		TDept dept = new TDept();
		
		Configuration config = new Configuration().configure();
		SessionFactory sessionFactory = config.buildSessionFactory();
		Session session = sessionFactory.openSession();
		
		// 通过ID 获取到一个对象;TDept.class 使用到java的反射机制;
		dept = (TDept) session.get(TDept.class, new Integer(p_id));
		
		session.close();
		return dept;
	}
	
	/*************************************************************************/
	/********************************
	 * 	增、删、改 :三种操作设计到数据的变化,则影响数据的安全性,所以需要使用事务以保证数据的
	 * 	安全性;
	 *	 
	 * 
	 * 
	 * 
	 ********************************/
	
	//增加
	public void addDept(TDept dept){
		Configuration config = new Configuration().configure();
		SessionFactory sessionFactory = config.buildSessionFactory();
		Session session = sessionFactory.openSession();
		Transaction ctx = session.beginTransaction();
		
		//增加session.save(dept);
		session.save(dept);
		
		ctx.commit();
		session.close();
	}
	
	//修改
	public void update(TDept dept){
		Configuration config = new Configuration().configure();
		SessionFactory sessionFactory = config.buildSessionFactory();
		Session session = sessionFactory.openSession();
		
		//开启事务
		Transaction ctx = session.beginTransaction();
		
		//修改:update();方法
		session.update(dept);
		
		//提交事务
		ctx.commit();
		session.close();
	}
	
	//删除
	public void delete(TDept dept){
		Configuration config = new Configuration().configure();
		SessionFactory sessionFactory = config.buildSessionFactory();
		Session session = sessionFactory.openSession();
		
		// 开启事务以保证数据的安全性;
		Transaction ctx = session.beginTransaction();
		
		//动作:delete(); 操作
		session.delete(dept);
		
		//提交事务
		ctx.commit();
		session.close();
	}
	
	public static void main(String[] args) {
		DeptDao_1 dao = new DeptDao_1();
		System.out.println(dao.getAll().size());
	}
}



中级:较为简化的连接方法:

package com.svse.dao;

import java.util.ArrayList;
import java.util.List;

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

import com.svse.entity.TUser;

//使用封装类简化代码进行操作
public class UserDao1 {

	//定义基本属性字段
	private static Configuration config = null;
	private static SessionFactory sessionFactory = null;
	private static Session session = null;
	private static Transaction ctx = null;

	//该内部类的特点:UserDao1这个实例化一次的时候自动的调用一次;
	static{
		try{
			config = new  Configuration().configure();
			sessionFactory = config.buildSessionFactory();
			session = sessionFactory.openSession();

		}catch(Exception ex){
			ex.printStackTrace();
		}
	}

	//增加
	public void addUser(TUser user){
		ctx = session.beginTransaction();
		session.save(user);
		ctx.commit();
		session.close();
	}

	//修改
	public void updateUser(TUser user){
		ctx = session.beginTransaction();
		session.update(user);
		ctx.commit();
		session.close();
	}

	//删除
	public void delUser(TUser user){
		ctx = session.beginTransaction();
		session.delete(user);
		ctx.commit();
		session.close();
	}

	//全查询
	public List getAll(){
		List ar = new ArrayList();
		ar = session.createQuery("FROM TUser").list();
		session.close();
		return ar;
	}

	//查询一个
	public TUser getOne(int u_id){
		TUser user = new TUser();
		user = (TUser) session.get(TUser.class, new Integer(u_id));
		session.close();
		return user;
	}


}



高级:最简单的方法,使用接口封装:

辅助类:


package com.svse.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {


    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}



定义接口规则:


package com.svse.util;

import org.hibernate.Session;

//结果定义规则
public interface IHibernateSessionFactorySupport {
	
	//得到Session
	public Session getSession();
	
	//开启事务
	public void beginTransaction();
	
	//提交事务
	public void commitTransaction();
	
	//关闭所有
	public void closeAll();
}



接口实现,编写规则:

package com.svse.util;

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

public class HibernateSessionFactorySupportImpl implements
		IHibernateSessionFactorySupport {

	//定义事务的对象:
	private Transaction ctx = null;
	
	//开启事务
	public void beginTransaction() {
		ctx = this.getSession().beginTransaction();
	}

	//提交事务
	public void commitTransaction() {
		try{
			ctx.commit();
		}catch(Exception ex){
			ex.printStackTrace();
			//事务回滚
			if(ctx!=null){
				ctx.rollback();
			}
		}finally{
			HibernateSessionFactory.closeSession();
		}
	}
	
	//关闭所有:调用自动生类中定义方法
	public void closeAll() {
		HibernateSessionFactory.closeSession();
	}

	//得到Session
	public Session getSession() {
		
		//返回一个Session的对象
		return HibernateSessionFactory.getSession();
	}

}


具体数据获取,访问数据库得到数据:

package com.svse.dao;

import java.util.List;

import com.svse.entity.TUser;
import com.svse.util.HibernateSessionFactorySupportImpl;

public class UserDao2 extends HibernateSessionFactorySupportImpl {
	
	//增加--涉及到数据的变化,需要使用事务
	public void addUser(TUser user){
		//第一步:开启事务
		this.beginTransaction();
		//第二步:执行动作
		this.getSession().save(user);
		//第三步:提交事务,并关闭相关的工具
		this.commitTransaction();
	}
	
	//修改
	public void updateUser(TUser user){
		//第一步:涉及到数据的安全性,先开启事务;
		this.beginTransaction();
		//第二步:获得Session对象并执行修改的动作;
		this.getSession().update(user);
		//第三步:提交事务,并关闭相关的工具;
		this.commitTransaction();
	}
	
	//删除
	public void delUser(int u_id){
		//1、开启事务
		this.beginTransaction();
		//2、执行动作
		this.getSession().delete(this.getOne(u_id));
		//3、提交事务:并关闭相关的工具
		this.commitTransaction();
	}
	
	//查询一个
	public TUser getOne(int u_id){
		//第一步:获取Session对象执行动作,得到集合对象获取数据;
		TUser user= (TUser) this.getSession().get(TUser.class, new Integer(u_id));
		//第二步:关闭Session工具;
		this.closeAll();
		return user;
		
	}
	
	//全查询
	public List getAll(){
		List ar = this.getSession().createQuery("FROM TUser").list();
		this.closeAll();
		return ar;
	}
	
	public static void main(String[] args) {
		UserDao2 dao = new UserDao2();
		TUser user = new TUser();
		user.setUId(1);
		user.setUName("小红aa");
		user.setUPwd("123");
		dao.updateUser(user);
	}
}




0
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics