您的位置:首页 > 其它

一.Hibernate配置环境搭建

2015-10-03 22:06 211 查看
1.导入jar包

包括lib\required 下所有jar包 根目录下hibernate3.jar(核心包)lib/jpa 下的包jdbc数据库包。

2.编写Hibernate.configure.xml配置文件(包括数据库的链接信息和关联映射可以从压缩包中找到)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect"> org.hibernate.dialect.Oracle10gDialect</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">accp</property>
<property name="connection.password">accp</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="cn/entity/Emp.hbm.xml" />
<mapping resource="cn/entity/Dept.hbm.xml" />
</session-factory>
</hibernate-configuration>


3.编写实体类(Xx.jar)和实体类映射文件(Xx.hbm.xml)将映射文件在配置文件中注入。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.entity" schema="">
<class name="Emp" table="EMP">
<!--主键-->
<id name="eno" type="java.lang.Integer">
<column name="ENO" length="8" />
<!--主键生成策略必须有-->
<generator class="sequence">
<param name="sequence">seq_dept</param>
</generator>
</id>
<property name="ename" type="java.lang.String">
<column name="ENAME" length="20" not-null="true" />
</property>

</class>
</hibernate-mapping>


4.编写session工厂来得到session(hibernate的session与servlet不同 )

package cn.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
* session工厂
* @author Administrator
*
*/
public class Sft {
private    static Session session;
/**开启会话
* @return
*/
public static Session getSession(){
Configuration config=new Configuration().configure();
SessionFactory session=config.buildSessionFactory().openSession();
return session;
}
public static void closeSession(){
if (session!=null) {
session.close();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: