Hibernate 1、Hello Hibernate

所使用到的jar 包:



1、创建实体类

public class User {

	private Integer id;
	private String name;
	private String address;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
}


2、配置映射文件

<hibernate-mapping>
	<class name="cn.model.User" table="USER" lazy="true">
		<id name="id" column="ID">
			<generator class="native"></generator>
		</id>
		<property name="name" column="NAME" type="java.lang.String" />
		<property name="address" column="ADDRESS" type="java.lang.String" />
	</class>
</hibernate-mapping>


3、配置hiberante.cfg.xml;hibernate.properties 详细 http://blog.csdn.net/oxiaoxio/article/details/49304591

<hibernate-configuration>
    <session-factory name="sessionFactory">
    	<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    	<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    	<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=UTF-8</property>
    	<property name="hibernate.connection.username">root</property>
    	<property name="hibernate.connection.password"></property>
    	<property name="hibernate.show_sql">true</property>
    	<property name="hibernate.format_sql">true</property>
    	<property name="hibernate.hbm2ddl.auto">update</property>

    	<mapping resource="cn/hbm/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


4、测试用例:

public class Conn {

	public void addUser(){
		Configuration cfg=new Configuration();
		cfg.configure();
		ServiceRegistry sr=new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
		SessionFactory sf=cfg.buildSessionFactory(sr);
		
		Session s=sf.openSession();
		Transaction trans=s.beginTransaction();
		User user=new User();
		user.setName("汤姆");
		user.setAddress("北海");
		s.save(user);
		trans.commit();
		s.close();
	}
}


代码优化:

新建一个类名字是HibernateSessionFactory:

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateSessionFactory {
	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() {
    }
	
    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;
    }

	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();
		}
	}

    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

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

	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static Configuration getConfiguration() {
		return configuration;
	}

}

优化过以后代码:

public void addUser(){
		Session s=HibernateSessionFactory.getSession();
		Transaction trans=s.beginTransaction();
		User user=new User();
		user.setName("汤姆11");
		user.setAddress("北海");
		s.save(user);
		trans.commit();
		s.close();
	}


posted @ 2015-10-21 17:21  Bodi  阅读(186)  评论(0编辑  收藏  举报