hibernateutil.java~4~

来自「struts教学程序,使用了struts,hibernate等相关技术,做简单的」· JAVA~4~ 代码 · 共 57 行

JAVA~4~
57
字号
package util.db;

import org.apache.commons.logging.*;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import strutsfinal.ProductForm;

public class HibernateUtil {

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

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static final ThreadLocal session = new ThreadLocal();

    public static Session currentSession() throws HibernateException {
        Session s = (Session) session.get();
        // Open a new Session, if this Thread has none yet
        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession() throws HibernateException {
        Session s = (Session) session.get();
        session.set(null);
        if (s != null)
            s.close();
    }
    public static void main(String[] args){
        Session session = HibernateUtil.currentSession();

       Transaction tx= session.beginTransaction();

       ProductForm princess = new ProductForm();
       princess.setProductname("测试商品");
       princess.setProductno("cssp");
       princess.setAmount(24);
       session.save(princess);
       tx.commit();
       HibernateUtil.closeSession();

    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?