Hibernate Dao的使用 Hibernate学习笔记(二)

/**
 * ------------Hibernate 官方推荐的写法,未作任何改动,需要熟记并融汇贯通---------------
 *
 * 主要是通过一个ThreadLocal实现当前线程共用一个Session
 *
 * 并不是单态的,可以自己改成单态
 */

package dao;

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

public class HibernateUtil {
    public static final SessionFactory       sessionFactory;
    // sessionFactory的作用是提供session
    static {
        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();// 构造一个sessionFactory,通过读取所有的hibernate配置文件
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    // ThreadLocal 本地线程 , 指当前线程的一个本地副本
    public static final ThreadLocal<Session> session = new ThreadLocal<Session>();

    // 本方法保证当前线程中只有一个Session的实例,并且获得它
    // 可以把Session理解成数据库连接 java.sql.Connection
    public static Session currentSession() throws HibernateException {
        Session s = session.get();// 从当前线程里面的到hibernate的Session
        if (s == null) {// 如果没得到
            s = sessionFactory.openSession();// 新建一个
            session.set(s);// 并且把它放到当前线程中去
        }
        return s;
    }

    // 关闭当前线程中的那一个Session
    public static void closeSession() throws HibernateException {
        Session s = session.get();
        if (s != null) {
            s.close();
        }
        session.set(null);
    }
}

 

下面的是对用户持久类的封装,不知道我这样理解对不对?上面的是参考的官网推荐的写法。

 

package dao;

import domain.User;

public class UserDao extends HibernateDao<User>
{
 public UserDao()
 {
  super(User.class);  
 }

}

 

 

使用dao更好的对数据库的操作进行了封装。对数据库操作更面向对象。但是不管是使用哪种方法都是有利有弊,还不能更彻底的做到封装,彻底的面向对象。

 

package app;

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

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

import dao.HibernateUtil;
import dao.UserDao;
import domain.Product;
import domain.ProductType;
import domain.Role;
import domain.User;

public class Test
{

 public static SessionFactory sessionFactory;
 
 public static void main(String[] args)
 {  
  sessionFactory = HibernateUtil.sessionFactory;  
 
  getPage();
 }
 
 static void getPage()
 {
  UserDao dao = new UserDao();
  List<User> list = dao.getAllPaged(2, 2);
  for(User u :list)
  {
   System.out.println(u.getName());
  }
 }

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值