Hibernate4标准配置

来源:互联网 发布:淘宝商城假货多吗 编辑:程序博客网 时间:2024/05/15 11:09

1.工具类 HibernateSessionFactory.java

package com.umgsai.test.test;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;import org.hibernate.tool.hbm2ddl.SchemaExport;/** * 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 {    /**     * Location of hibernate.cfg.xml file.     * Location should be on the classpath as Hibernate uses     * #resourceAsStream style lookup for its configuration file.     * The default classpath location of the hibernate config file is     * in the default package. Use #setConfigFile() to update     * the location of the configuration file for the current session.      */    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();    private static org.hibernate.SessionFactory sessionFactory;                             private static Configuration configuration = new Configuration();    private static ServiceRegistry serviceRegistry;    static {        try {            configuration.configure();            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();            sessionFactory = configuration.buildSessionFactory(serviceRegistry);        } 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();            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();            sessionFactory = configuration.buildSessionFactory(serviceRegistry);        } 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 hibernate configuration     *     */    public static Configuration getConfiguration() {        return configuration;    }}

2.实体类

package com.umgsai.test.entity;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import org.hibernate.annotations.GenericGenerator;@Entity@Table(name="t_user")public class User {    @GenericGenerator(name = "generator", strategy = "increment")    @Id    @GeneratedValue(generator = "generator")    @Column(name = "id", unique = true, nullable = false)    private int id;    private String username;    private String password;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }}

3.hibernate配置文件

<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools.                   --><hibernate-configuration><session-factory>    <property name="myeclipse.connection.profile">mysql</property>    <property name="connection.url">        jdbc:mysql://localhost:3306/myeclipse?createDatabaseIfNotExist=true    </property>    <property name="connection.username">root</property>    <property name="connection.password">123456</property>    <property name="connection.driver_class">        com.mysql.jdbc.Driver    </property>    <property name="dialect">        org.hibernate.dialect.MySQLDialect    </property>    <property name="javax.persistence.validation.mode">none</property>    <property name="hibernate.hbm2ddl.auto">update</property>    <property name="hibernate.show_sql">true</property>    <property name="hibernate.format_sql">true</property>    <mapping class="com.umgsai.test.entity.User"/>          </session-factory></hibernate-configuration>

4.测试类

package com.umgsai.test.test;import org.hibernate.Session;import org.hibernate.Transaction;import com.umgsai.test.entity.User;public class Test {    public static void main(String[] args) {        // TODO Auto-generated method stub        User user = new User();        user.setUsername("umgsai");        user.setPassword("123456");        Session session = HibernateSessionFactory.getSession();        Transaction transaction = null;        try {            transaction = session.beginTransaction();            session.save(user);            transaction.commit();        } catch (Exception e) {            // TODO: handle exception            transaction.rollback();            e.printStackTrace();        }finally{            HibernateSessionFactory.closeSession();        }    }}


本文出自 “优赛工作室” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1362937

0 0
原创粉丝点击