标签:
1.导入jar包
包括lib\required 下所有jar包 根目录下hibernate3.jar(核心包)lib/jpa 下的包jdbc数据库包。
2.编写Hibernate.configure.xml配置文件(包括数据库的链接信息和关联映射可以从压缩包中找到)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <property name="dialect"> org.hibernate.dialect.Oracle10gDialect</property> 8 <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> 10 <property name="connection.username">accp</property> 11 <property name="connection.password">accp</property> 12 <property name="show_sql">true</property> 13 <property name="format_sql">true</property> 14 <mapping resource="cn/entity/Emp.hbm.xml" /> 15 <mapping resource="cn/entity/Dept.hbm.xml" /> 16 </session-factory> 17 </hibernate-configuration>
3.编写实体类(Xx.jar)和实体类映射文件(Xx.hbm.xml)将映射文件在配置文件中注入。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping package="cn.entity" schema=""> 6 <class name="Emp" table="EMP"> 7 <!--主键--> 8 <id name="eno" type="java.lang.Integer"> 9 <column name="ENO" length="8" /> 10 <!--主键生成策略必须有--> 11 <generator class="sequence"> 12 <param name="sequence">seq_dept</param> 13 </generator> 14 </id> 15 <property name="ename" type="java.lang.String"> 16 <column name="ENAME" length="20" not-null="true" /> 17 </property> 18 19 </class> 20 </hibernate-mapping> 21
4.编写session工厂来得到session(hibernate的session与servlet不同 )
1 package cn.util; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 7 /** 8 * session工厂 9 * @author Administrator 10 * 11 */ 12 public class Sft { 13 private static Session session; 14 /**开启会话 15 * @return 16 */ 17 public static Session getSession(){ 18 Configuration config=new Configuration().configure(); 19 SessionFactory session=config.buildSessionFactory().openSession(); 20 return session; 21 } 22 public static void closeSession(){ 23 if (session!=null) { 24 session.close(); 25 } 26 27 } 28 }
标签:
原文地址:http://www.cnblogs.com/wanghongjie/p/4853917.html