注:本文项目文件在https://github.com/SpaceyLi/hibernate_test2
一、下载
首先需要到官网http://hibernate.org/下载hibernate包(本文使用4.3.5)。
环境说明:
IDE:MyEclipse9.1
JDK:1.6.0_45
Tomcat:7.0.42
二、创建工程
创建工程hibernate_test2(Web Project),本文的项目路径为E:\MyEclipse\hibernate_test2,在J2EE Specification Level选项中选择Java EE 6.0。
三、配置
1.项目建好后把事先下载好的hibernate包解压后打开,将hibernate-release-4.3.5.Final\lib\required中的所有jar包copy到项目的hibernate_test2/WebRoot/WEB-INF/lib文件夹下,然后刷新项目。就可以在MyEclipse的Package Explorer窗口中看到这些库文件。
2.在src下创建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"> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_test</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="myeclipse.connection.profile">hibernate_test</property> <property name="show_sql">true</property> <!-- student --> <mapping resource="org/spacey/bean/Student.hbm.xml" /> </session-factory> </hibernate-configuration>
数据库用的mysql,数据库名为hibernate_test,用户名密码都为root,最后引入Student表的配置文件:
"org/spacey/bean/Student.hbm.xml"
该文件我们稍后再添加。
3.在package org.spacey.db下创建HibernateSessionFactory.java类:
package org.spacey.db; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public class HibernateSessionFactory { private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); 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; } }
唯一需要注意的地方是:
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
/hibernate.cfg.xml即为刚刚的配置文件的路径。
4.在package org.spacey.bean下创建Student.java类:
package org.spacey.bean; public class Student { private long id; private String sname; private String snum; private String sex; private String email; /** default constructor */ public Student() { } /** minimal constructor */ public Student(long id, String sname, String snum) { this.id = id; this.sname = sname; this.snum = snum; } /** half constructor */ public Student(String sname, String snum, String sex, String email) { this.sname = sname; this.snum = snum; this.sex = sex; this.email = email; } /** full constructor */ public Student(long id, String sname, String snum, String sex, String email) { this.id = id; this.sname = sname; this.snum = snum; this.sex = sex; this.email = email; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getSnum() { return snum; } public void setSnum(String snum) { this.snum = snum; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
5.在org.spacey.bean下创建Student.hbm.xml文件,即为我们上面提到的Student配置文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="org.spacey.bean.Student" table="student" catalog="hibernate_test"> <id name="id" type="long"> <column name="id" length="32" /> <generator class="increment" /> </id> <property name="sname" type="java.lang.String"> <column name="sName" length="20" not-null="true" /> </property> <property name="snum" type="java.lang.String"> <column name="sNum" length="20" not-null="true" /> </property> <property name="sex" type="java.lang.String"> <column name="sex" length="2" /> </property> <property name="email" type="java.lang.String"> <column name="email" length="30" /> </property> </class> </hibernate-mapping>
该文件的作用就是将数据库hibernate_test中数据表Student的信息与类Student进行匹配。
6.在数据库中创建表Student(这一步可以在创建项目之前就先做好):
首先需要创建数据库hibernate_test
CREATE DATABASE IF NOT EXISTS `hibernate_test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
然后再创建表student
CREATE TABLE IF NOT EXISTS `student` ( `id` bigint(32) NOT NULL AUTO_INCREMENT, `sName` varchar(20) NOT NULL, `sNum` varchar(20) NOT NULL, `sex` varchar(2) DEFAULT NULL, `email` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) );
7.编写测试类:org.spacey.test.TestHibernate.java
package org.spacey.test; import org.hibernate.Session; import org.hibernate.Transaction; import org.spacey.bean.Student; import org.spacey.db.HibernateSessionFactory; public class TestHibernate { public static void main(String[] args) { Session session = HibernateSessionFactory.getSession(); if (session == null) System.out.println("init error"); Transaction tx = session.beginTransaction(); Student stu = new Student("test","test","1","test"); try { session.save(stu); tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } finally { session.close(); } } }
然后Run As Java Application就可以在数据库中看到hibernate_test.student中多了一条记录。