hibernate.cfg.xml配置文件内容如下,注意一点的是,当你想运行时就自动建表,而不用再到数据库用SQL来创建数据库的话,就要在<session-factory>标签内加入如下配置信息:

<property name="hbm2ddl.auto">create</property>

当hibernate与spring集成在一起,没有单独的hibernate.cfg.xml文件时,就要在spring配置文件里的sessionFactory标签里,配置如下信息:

<property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        <prop key="hbm2ddl.auto">update</prop></props>  
</property>


首先介绍其中的一个属性hbm2ddl.auto,这个就是这个方案的核心属性,有四个值:create,create-drop,update,validate。它的含义如下:


<!-- 启动时删数据库中的表,然后创建,退出时不删除数据表
<property name="hbm2ddl.auto">create</property> -->
<!-- 启动时删数据库中的表,然后创建,退出时自动删除所有表
<property name="hbm2ddl.auto">create-drop</property> -->
<!-- 自动修改,如果表结构与实体类不一致,那么就修改表使它们一致,数据会保留
<property name="hbm2ddl.auto">update</property> -->
<!-- 自动校验,如果表结构与实体类不一致,那么不做任何操作,报错
<property name="hbm2ddl.auto">validate</property> -->


 

 

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">

	<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

	<session-factory>
		<!-- 各属性的配置-->
		
		<!-- 启动时删数据库中的表,然后创建,退出时不删除数据表,如果没有下面的属性的话,那么要手动写sql语句来建表,才能进行数据库的操作-->
		<property name="hbm2ddl.auto">create</property>
		
		<!--为true表示将Hibernate发送给数据库的sql显示出来 -->
		<property name="show_sql">true</property>
		
		<!-- SQL方言,这边设定的是MySQL -->
		<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

		<!-- 一次读的数据库记录数 -->
		<property name="jdbc.fetch_size">50</property>

		<!-- 设定对数据库进行批量删除 -->
		<property name="jdbc.batch_size">30</property>

		<!--驱动程序-->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>

		<!-- JDBC URL -->
		<property name="connection.url">jdbc:mysql://localhost/testWTB?characterEncoding=gb2312</property>

		<!-- 数据库用户名-->
		<property name="connection.username">root</property>

		<!-- 数据库密码-->
		<property name="connection.password"></property>

		<!--映射文件 -->
		<!--  
		<mapping resource="com/amigo/pojo/User.hbm.xml" />
		<mapping resource="com/amigo/pojo/Org.hbm.xml" />
		-->
		<mapping class="com.ajax.employee.model.Employee"/> 
		
	</session-factory>

</hibernate-configuration>

 

实体类Employee.java

package com.ajax.employee.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;

@Entity
@Table(name = "EMPLOYEE")
public class Employee implements java.io.Serializable{
	
	private Integer employee_id; //人员ID(主键)
	private String employee_name; //人员姓名
	private String sex; //性别
	private String birthday; //出生日期
	private String address; //地址
	
	@Id
	@Column(name = "EMPLOYEE_ID")
	@TableGenerator(
	     name="tab-store",//产生器的名字,也就是下面的generator的名字
	     table="GENERATOR_TABLE",//产生器的table名
	     pkColumnName = "G_KEY",//与employee这张表关联的外键列名
	     pkColumnValue="EMPLOYEE_PK",//向这generator表的这个与employee表关联的列的值赋为EMPLOYEE_PK
	     valueColumnName = "G_VALUE",//外键参考的值
	     allocationSize=1//产生器表的初始值,这个值是指id的初始值,当插入第一条记录后,那么这条记录分配到的id值为1,而在generator_table表里的G_VALUE一栏的值变为2,即它是下一次插入记录的id准备值
	)
	@GeneratedValue(strategy = GenerationType.TABLE,generator="tab-store")//用表产生器来产生id值,这样会在数据新建表产生器表,产生器表记录只有一条,很简单,只用来记录下一个分配出去id值为多少
//	@GeneratedValue(strategy = GenerationType.AUTO)
	public Integer getEmployee_id() {
		return employee_id;
	}
	public void setEmployee_id(Integer employee_id) {
		this.employee_id = employee_id;
	}
	public String getEmployee_name() {
		return employee_name;
	}
	public void setEmployee_name(String employee_name) {
		this.employee_name = employee_name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
}

DAO类:

package com.ajax.core;

import java.io.Serializable;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * 抽象Dao类,用于持久化操作
 * @author 菠萝大象
 * @version 1.0
 */
public abstract class BaseDao<T> {

	private static Log log = LogFactory.getLog(BaseDao.class);
	
	/**
	 * 获取Hibernate的Session对象
	 */
	public Session getSession(){
        return HibernateSessionFactory.getSession();
    }
	
	/**
     * 根据主键得到对象
     */
	public T getObject(Class clazz, Serializable id){
		return (T)getSession().get(clazz, id);
	}
	
	/**
	 * 保存对象
	 */
	public void saveObject(T t) {
		Session session = getSession();
		Transaction tx = beginTransaction(session);
		try{
			session.saveOrUpdate(t);
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			log.error("保存对象失败");
		}
	}
	
	/**
	 * 更新对象
	 */
	public void updateObject(T t){
		Session session = getSession();
		Transaction tx = beginTransaction(session);
		try{
			session.update(t);
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			log.error("更新对象失败");
		}
	}
	
	/**
	 * 删除对象
	 */
	public void removeObject(T t) {
		Session session = getSession();
		Transaction tx = beginTransaction(session);
		try{
			session.delete(t);
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			log.error("删除对象失败");
		}
	}
	
	/**
     * 根据主键删除对象
     */
	public void removeObject(Class clazz, Serializable id){
		Session session = getSession();
		Transaction tx = beginTransaction(session);
		try{
			session.delete(getObject(clazz, id));
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			log.error("根据主键删除对象失败");
		}
	}
	
	/**
	 * 创建事务
	 */
	private Transaction beginTransaction(Session session){
		return session.beginTransaction();
	}
}

 HibernateSessionFactory.java

package com.ajax.core;

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

/**
 * 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 String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static AnnotationConfiguration configuration = new AnnotationConfiguration(); //这里需要修改
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} 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(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} 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 session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

由于使用到hibernate注解方式,所以这里在用到hibernate-annotations-3.3.0.jar和hibernate-commons-

annotations-3.0.0.jar包,还需要如下的包(具体的版本可以选择最新的):
asm-1.5.3.jar
cglib-2.1.3.jar
commons-collections-2.1.1.jar
commons-lang-2.1.jar
commons-logging-1.1.jar
dom4j-1.6.1.jar
hibernate3-3.2.5.jar
mysql-connector.jar

使用上面方式就可以构建简单的hibernate访问数据库了。