hibernate 起步学习

导包等工作之后:

第一步配置:hibernate.cfg.xml

<?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="dialect">org.hibernate.dialect.MySQLDialect</property>
      <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
      <property name="connection.username">root</property>
      <property name="connection.password">root</property>
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
     
      <property name="show_sql">true</property>
     
      <mapping resource="liu/javatest/hibernate/model/User.hbm.xml" />
   
     </session-factory>

</hibernate-configuration>

 

第二:javabean  user  user.hbm.xml


User.java

 

import java.io.Serializable;

public class User implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private String id;
    private String username;
    private String password;

    public User() {

    }

    /**
     * @return the id
     */
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the username
     */
    public String getUsername() {
        return username;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
   
}

第三:操作

 

/**
 *
 */
import java.util.List;

import liu.javatest.hibernate.model.User;
import liu.javatest.hibernate.util.HibernateUtil;

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

import com.sun.rowset.internal.Row;

/**
 * @author 933soft
 *
 */
public class OperateUser implements java.io.Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    /**
     *
     */
    public OperateUser() {
        // TODO Auto-generated constructor stub
    }
    /**
     * 添加用户信息
     * @param user
     * @throws Exception
     */
    public static void insertUser(User user)throws Exception{
       
        Session session = HibernateUtil.getCurrentSession() ;
        Transaction tx = session.beginTransaction() ;
        session.save(user) ;
        tx.commit() ;
        HibernateUtil.closeSession() ;
       
    }
    public static void main(String[] args)throws Exception{
   
        /*Session session = HibernateUtil.getCurrentSession() ;
        Transaction tx = session.beginTransaction() ;
        for (int i = 0; i < 200; i++) {
              User user = new User() ;
                user.setPassword("abc"+i) ;
                user.setUsername("测试"+i) ;
                session.save(user) ;
          }
        tx.commit() ;
        session.close() ;*/
       
        SessionFactory sf = new Configuration().configure().buildSessionFactory() ;
        Session session = sf.openSession() ;
        Transaction tx = session.beginTransaction() ;
        Query query = session.createQuery(" from User where username=:name ") ;
        query.setString("name", "测试") ;
        List list = query.list() ;
        tx.commit() ;
        session.close() ;
        List<User> listUser = (List<User>) list ;
        int i=0 ;
        for(User user:listUser){
            System.out.println("==="+i+"===="+user.getId()) ;
            System.out.println("==="+i+"===="+user.getPassword()) ;
            System.out.println("==="+i+"===="+user.getUsername()) ;
            i++ ;
        }       
    }
/**
     * 删除用户信息
     * @param user
     * @throws Exception
     */
    public void deleteUser(User user)throws Exception{
       
        Session session = HibernateUtil.getCurrentSession() ;
        Transaction tx = session.beginTransaction() ;
        session.delete(user) ;
        tx.commit() ;
        HibernateUtil.closeSession() ;
   
    }
   
    /**
     * 更新用户信息
     * @param user
     * @throws Exception
     */
    public void updateUser(User user)throws Exception{
       
        Session session  = HibernateUtil.getCurrentSession() ;
        Transaction tx = session.beginTransaction() ;
        session.saveOrUpdate(user) ;
        tx.commit() ;
        HibernateUtil.closeSession() ;
   
    }
    /**
     * 查询单位
     * @param ids
     * @return
     */
    public static List getUsers(){
       
        Session session = HibernateUtil.getCurrentSession() ;
        Transaction tx = session.beginTransaction() ;
        String hql = "select new User(password) from model.User" ;
        Query query = session.createQuery(hql) ;
        List list = query.list() ;
        tx.commit() ;
        HibernateUtil.closeSession() ;
       
        return list  ;
    }

}

 

当让可以写HibernateUtil

 

import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Interceptor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.transaction.CMTTransactionFactory;

/**
 *
 * @author 933soft
 *
 *
 * Hibernate 工具类 用于初始化Hibernate,并进行Session和Transaction的管理
 *
 */
public class HibernateUtil {

    private static Log log = LogFactory.getLog(HibernateUtil.class);

    private static final String INTERCEPTOR_CLASS = "hibernate.util.interceptor_class";

    private static Configuration configuration;

    private static SessionFactory sessionFactory;

    private static boolean useThreadLocal = true;

    // 保存Session对象实例的线程局部变量
    private static ThreadLocal threadSession = new ThreadLocal();

    // 保存Transaction对象实例的线程局部变量
    private static ThreadLocal threadTransaction = new ThreadLocal();

    static {
        try {
            // 创建Configuration对象
            configuration = new Configuration();

            // 读取hibernate.properties或者hibernate.cfg.xml文件
            configuration.configure();

            // 指定一个全局的用户子定义的拦截器
            String interceptorName = configuration
                    .getProperty(INTERCEPTOR_CLASS);
            if (interceptorName != null) {
                Class interceptorClass = HibernateUtil.class.getClassLoader()
                        .loadClass(interceptorName);
                Interceptor interceptor = (Interceptor) interceptorClass
                        .newInstance();
                configuration.setInterceptor(interceptor);
            }

            // 如果使用CMT,那么就不使用线程安全的Session和Transaction
            if (CMTTransactionFactory.class
                    .getName()
                    .equals(
                            configuration
                                    .getProperty(Environment.TRANSACTION_STRATEGY))) {
                useThreadLocal = false;
            }

            if (configuration.getProperty(Environment.SESSION_FACTORY_NAME) != null) {
                // 绑定Hibernate到JNDI
                configuration.buildSessionFactory();
            } else {
                // 使用静态的变量
                sessionFactory = configuration.buildSessionFactory();
            }
        } catch (Throwable ex) {
            // 必须捕获Throwable,否则不能捕获NoClassDefFoundError异常以及它的子类错误
            log.error("Building SessionFactory failed!", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    /**
     * 返回全局的SessionFactory对象的实例
     *
     * @return SessionFactory
     */
    public static SessionFactory getSessionFactory() {
        SessionFactory sf = null;
        String sfName = configuration
                .getProperty(Environment.SESSION_FACTORY_NAME);
        if (sfName != null) {
            log.debug("Looking up SessionFactory in JNDI.");
            try {
                sf = (SessionFactory) new InitialContext().lookup(sfName);
            } catch (NamingException e) {
                throw new RuntimeException(e);
            }
        } else {
            sf = sessionFactory;
        }
        if (sf == null) {
            throw new IllegalStateException("SessionFactory not available.");
        }
        return sf;
    }

    /**
     * 重新构建SessionFactory对象的实例
     *
     */
    public static void rebuildSessionFactory() {
        log.debug("Using current Configuration for rebuild");
        rebuildSessionFactory(configuration);
    }

    /**
     * 使用指定的Configuration对象重新构建SessionFactory对象的实例
     *
     * @param cfg
     */
    public static void rebuildSessionFactory(Configuration cfg) {
        log.debug("Rebuilding the SessionFactory from given Configuration.");
        synchronized (sessionFactory) {
            if (sessionFactory != null && !sessionFactory.isClosed()) {
                sessionFactory.close();
            }
            if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) {
                cfg.buildSessionFactory();
            } else {
                sessionFactory = cfg.buildSessionFactory();
            }
            configuration = cfg;
        }
    }

    /**
     * 关闭当前SessionFactory并且释放所有资源
     *
     */
    public static void shutdown() {
        log.debug("Shutting down Hibernate.");
        // 关闭缓冲和连接池
        getSessionFactory().close();

        // 清除静态变量
        configuration = null;
        sessionFactory = null;

        // 清除本地进程变量
        threadSession.set(null);
        threadTransaction.set(null);
    }

    /**
     * 获得当前Session对象的实例
     *
     * @return Session
     */
    public static Session getCurrentSession() {
        if (useThreadLocal) {
            Session s = (Session) threadSession.get();
            if (s == null) {
                log.debug("Opening new Session for this thread.");
                s = getSessionFactory().openSession();
                threadSession.set(s);
            }
            return s;
        } else {
            return getSessionFactory().getCurrentSession();
        }
    }

    /**
     * 重新连接当前的Session
     *
     * @param session
     */
    public static void reconnect(Session session) {
        if (useThreadLocal) {
            log.debug("Reconnecting Session to this thrwad.");
            session.reconnect();
            threadSession.set(session);
        } else {
            log
                    .error("Using CMT/JTA,intercepted not supported reconnect call.");
        }
    }

    /**
     * 断开当前Session
     *
     * @return Session the disconnected Session
     */
    public static Session disconnectedSession() {
        if (useThreadLocal) {
            Transaction tx = (Transaction) threadTransaction.get();
            if (tx != null && (!tx.wasCommitted() || !tx.wasRolledBack())) {
                throw new IllegalStateException(
                        "Disconnecting Session but Transaction still open.");
            }
            Session session = getCurrentSession();
            threadSession.set(null);
            if (session.isConnected() && session.isOpen()) {
                log.debug("Disconnecting Session from this thread.");
                session.disconnect();
            }
            return session;
        } else {
            log
                    .error("Using CMT/JTA,intercepted not supported disconnect call.");
            return null;
        }
    }

    /**
     * 关闭Session对象
     *
     */
    public static void closeSession() {
        if (useThreadLocal) {
            Session s = (Session) threadSession.get();
            threadSession.set(null);
            Transaction tx = (Transaction) threadTransaction.get();
            if (tx != null && (!tx.wasCommitted() || !tx.wasRolledBack())) {
                throw new IllegalStateException(
                        "Closing Session but Transaction still open.");
            }
            if (s != null && s.isOpen()) {
                log.debug("Closing Session of this thread.");
                s.close();
            }
        } else {
            log.warn("Using CMT/JTA,intercepted superfluous close call.");
        }
    }

    /**
     * 开始一个新的数据库事务
     *
     */
    public static void beginTransaction() {
        if (useThreadLocal) {
            Transaction tx = (Transaction) threadTransaction.get();
            if (tx == null) {
                log.debug("Starting new database transaction in this thread.");
                tx = getCurrentSession().beginTransaction();
                threadTransaction.set(tx);
            }

        } else {
            log.warn("Using CMT/JTA,intercepted superfluous tx begin call.");
        }
    }

    /**
     * 提交数据库事务
     *
     */
    public static void commitTransaction() {
        if (useThreadLocal) {
            try {
                Transaction tx = (Transaction) threadTransaction.get();
                if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                    log
                            .debug("Committing database transaction of this thread.");
                    tx.commit();
                }
                threadTransaction.set(null);
            } catch (RuntimeException e) {
                log.error(e);
                rollbackTransaction();
                throw e;
            }
        } else {
            log.warn("Using CMT/JTA,intercepted superfluous tx commit call.");
        }
    }

    /**
     * 回滚数据库事务
     *
     */
    public static void rollbackTransaction() {
        if (useThreadLocal) {

            Transaction tx = (Transaction) threadTransaction.get();
            try {
                threadTransaction.set(null);
                if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) {
                    log
                            .debug("Trying to rollback database transaction of this thread.");
                    tx.rollback();
                }
            } catch (RuntimeException e) {
                throw new RuntimeException(
                        "Migth swallow original cause,check Error log!", e);
            } finally {
                closeSession();
            }
        } else {
            log.warn("Using CMT/JTA,intercepted superfluous tx rollback call.");
        }
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值