<?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="connection.driver_class"><!-- 配置数据库的驱动类 -->
oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url"><!-- 配置数据库的连接路径 -->
jdbc:oracle:thin:@localhost:1521:orcl
</property>
<property name="connection.username">test</property><!-- 配置数据库的连接用户名 -->
<property name="connection.password">test</property><!-- 配置数据库的连接密码,这里密码为空,在这种情况下也可以省略该行配置代码 -->
<property name="dialect"><!-- 配置数据库使用的方言 -->
org.hibernate.dialect.OracleDialect
</property>
<property name="show_sql">true</property><!-- 配置在控制台显示SQL语句 -->
<property name="format_sql">true</property><!-- 配置对输出的SQL语句进行格式化 -->
<property name="use_sql_comments">true</property><!-- 配置在输出的SQL语句前面添加提示信息 -->
<mapping resource="com/mwq/hibernate/mapping/TbDept.hbm.xml" /><!-- 配置持久化类映射文件 -->
</session-factory>
</hibernate-configuration>
TbRecord record = (TbRecord) dao.queryRecordByNum(userNum);
public Object queryRecordByNum(String num) {
return this.queryObject("from TbRecord where record_number='" + num
+ "'");
}
查询配置:
protected Object queryObject(String hql) {
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery(hql);
Object object = query.uniqueResult();
return object;
}
保存配置:
// save
public boolean saveObject(Object obj) {
boolean isSave = true;
Session session = HibernateSessionFactory.getSession();
Transaction tr = session.beginTransaction();
try {
session.save(obj);
tr.commit();
} catch (HibernateException e) {
isSave = false;
e.printStackTrace();
}
return isSave;
}
package com.mwq.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static SessionFactory sessionFactory;
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
static {
try {
Configuration config = new Configuration().configure();
sessionFactory = config.buildSessionFactory();
} catch (Exception e) {
System.out.println("------在加载Hibernate配置文件时抛出异常,内容如下:");
e.printStackTrace();
}
}
public static Session getSession() {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null || session.isOpen()) {
session.close();
}
}
}