hibernate步骤
1.读取并解析配置文件及映射文件
Configuration conf=new Configuration().configure();
2.依据配置文件和映射文件中的信息,创建SessionFactory对象 1.2.3通常写在HbiernateUtil静态方法中
SessionFactory sf=conf.buildSessionFactory(); 并在Dao层中返回session
3.打开session
Session session=sf.getCurrentSession()
4.开始一个事务
Transaction tx=session.beginTransaction()
5.数据库操作
session.save(user);
delete
update
6.结束事务
tx.commit()
7.如果是openSission().则需要session.close()
hibernate.cfg.xml
<?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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="myeclipse.connection.profile">orcl</property>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.password">tiger</property>
<property name="connection.username">scott</property>
<property name="connection.url">
jdbc:oracle:thin:@127.0.0.1:1521:orcl
</property>
<property name="connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="entities/BlogBlog.hbm.xml" />
<mapping resource="entities/BlogUser.hbm.xml" />
</session-factory>
</hibernate-configuration>
entity.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="entities.BlogBlog" table="BLOG_BLOG" schema="SCOTT">
<id name="id" type="java.lang.Long">
<column name="ID" precision="10" scale="0" />
<generator class="assigned" />
</id>
<many-to-one name="blogUser" class="entities.BlogUser" fetch="select">
<column name="USERID" precision="10" scale="0" not-null="true" />
</many-to-one>
<property name="content" type="java.lang.String">
<column name="CONTENT" length="1000" not-null="true" />
</property>
<property name="publishtime" type="java.lang.String">
<column name="PUBLISHTIME" not-null="true" />
</property>
</class>
</hibernate-mapping>
public class HibernateUtil{
private static Configuration configuration;
private final static SessionFactory sessionFactory;
static{
try{
configuration=new Configuration().configure();
sessionFactory=configuration.buildSessionFactory();
}catch(HibernateException ex){
throw new ExceptionInInitializeError(ex)}}
privateHibernateUtil(){}
public static Session currentSession(){return sessionFactory.getCurrentSession();}
}