单纯Hibernate环境的搭建

单纯Hibernate环境的搭建

所谓单纯Hibernate环境,是指不与Spring集成而单独使用Hibernate在完成持久层工作的环境的搭建

习惯了SSH集成的小盆友可能不太记得如何单独使用Hibernate了

搭建步骤:

1.引入JDBC驱动jar包和Hibernate的Jar包

2.在src中创建Hibernate的配置文件(使用MyEclipse的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="myeclipse.connection.profile">mysql</property>
	<property name="connection.url">
		jdbc:mysql://localhost:3306/edu
	</property>
	<property name="connection.username">root</property>
	<property name="connection.password"></property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="format_sql">true</property>
	<property name="show_sql">true</property>
	<property name="hbm2ddl.auto">create</property>
	<mapping resource="com/edu/conf/hibernate/hbm/user.hbm.xml" />
</session-factory>
</hibernate-configuration>

3.创建映射文件,并添加到配置文件

4.实现Dao,典型的Hibernate的初始化代码

public class BaseDao {
	private static SessionFactory sf = null;
	//加载SessionFactory
	static {
		sf = new Configuration()
		.configure("com/edu/conf/hibernate/hiernate.xml")
		.buildSessionFactory();
	}
	public Session getSession(){
		return sf.openSession();
	}
}
public class UserDao extends BaseDao{
	public boolean addUser(User user){
		Session session = this.getSession();
		Transaction trans = session.beginTransaction();
		session.save(user);
		trans.commit();
		return true;
	}
}

相关推荐