Hibernate学习笔记(1)

时间:2023-03-09 21:36:50
Hibernate学习笔记(1)

1 使用Hibernate

(1)创建User Library,命名为HIBERNATE3,加入需要的jar

(2)创建hibernate配置文件hibernate.cfg.xml, 为了便于调试最好加入log4j配置文件log4j.properties。(这两个文件可从下载的hibernate中的project里找到)

2 运行调试时显示Sql语句:

在hibernate.cfg.xml里添加hibernate.show_sql属性。

<session-factory name="foo">
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="com/bpf/hibernate/User.hbm.xml"/>
</session-factory>

3 使用Hibernate的7个步骤

Hibernate学习笔记(1)
     Configuration conf = new Configuration().configure(); //加载hibernate.cfg.xml文件
SessionFactory sf = conf.buildSessionFactory(); //创建SessionFactory 一个SessionFactory对应一个数据库
Session sess = null;
Transaction tx = null;
try{
sf.openSession(); //创建打开Session
tx = sess.beginTransaction(); //开始事务 //持久化操作
User u = new User();
u.setName("zhang");
u.setCreateTime(new Date());
u.setExpireTime(new Date());
sess.save(u); tx.commit();//提交事务
}
catch(Exception e){
e.printStackTrace();
tx.rollback(); //回滚事务
}
finally{
if(sess != null && sess.isOpen()){
sess.close(); //关闭session
sf.close();
}
}
Hibernate学习笔记(1)