版权声明: https://blog.csdn.net/wz1989love/article/details/84255510
加载配置文件
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
上图中配置文件位置为src根目录,可以用绝对路径。
配置文件如下:
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!-- 对应DB Browser里配置的数据库信息 -->
<property name="myeclipse.connection.profile">demo</property>
<!-- 方言:为每一种数据库提供适配器,方便转换 -->
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<!-- 数据库驱动 -->
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<!-- 数据库名称 -->
<property name="connection.url">jdbc:oracle:thin:@192.168.70.10:1521:orcl</property>
<!-- 数据库的登陆用户名 -->
<property name="connection.username">masceshi</property>
<!-- 数据库的登陆密码 -->
<property name="connection.password">masceshi</property>
<!-- 打印SQL语句 -->
<property name="show_sql">true</property>
<!-- 打印SQL语句格式化输出 -->
<property name="format_sql">true</property>
<!-- 数据库与实体对应配置 -->
<!-- 如果不加会报org.hibernate.MappingException: Unknown entity: com.hibernate.demo.entity.Student -->
<mapping class="com.hibernate.demo.entity.Student" />
</session-factory>
</hibernate-configuration>
创建sessionFactory
SessionFactory factory = cfg.buildSessionFactory();
获取sessionFactory方法在各个版本中各不相同。注意:笔者使用的Hibernate版本为myeclipse2017自带的5.1版本,其他低版本经测试在单元测试时无法正确获取sessionFactory,该问题未解决,可能是由于笔者使用的均为myeclipse自带的版本。
创建session
Session session = factory.openSession();
开启事务
session.beginTransaction();
执行操作
Student student = new Student();
student.setName("张三");
student.setAge("21");
student.setId("21");
session.persist(student);
提交事务
session.getTransaction().commit();
在正常代码编写时,会用try/catch捕获业务操作中产生的异常,并在报错后对事务进行回滚,无论是否执行成功都需要手动关闭session。
@Test
public void save1() {
Session session = null;
try {
session = HibernateUtils.getSession();
session.beginTransaction();
Student student = new Student();
student.setName("张三");
student.setAge("21");
student.setId("21");
session.persist(student);
session.getTransaction().commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
session.getTransaction().rollback();
} finally {
HibernateUtils.closeSession(session);
}
}