Hiberante3.6的入门使用

来源:互联网 发布:java培训出来没底气 编辑:程序博客网 时间:2024/06/05 10:59

1、Hibernate3.6的主要AIP组件

1.1 Configuration:用于配置并且启动Hibernate框架

每个Hibernate配置文件对应一个Configuration对象。Hibernate通过Configuration实例的configure()方法读取配置文件Hibernate.cfg.xml,在通过Configuration实例的buildSessionFactory()方法创建SessionFactory实例。

Configuration configuration=new Configuration().configure();

1.2 SessionFactory:会话工厂

一个SessionFactory实例对应一个数据源,即一个数据库。

SessionFactory sessionFactory=configuration.buildSessionFactory();

1.3 Session:会话管理器,简称“会话”

一个Session实例完成一次会话,一次会话就是一次对数据库的访问。应用程序通过SessionFactory的openSession()方法或getCurrentSession()方法中获得Session实例。

Session session=sessionFactroy.openSession();

1.4 Query:查询组件

Query用于从数据库中查询对象,并控制执行查询的过程。Query包装了HQL查询语句,HQL查询语句是变面向对象的,它引用类名及类的属性名,而不是应用表名及字段名。

通过Session实例的createQuery()方法创建Query实例,典型的语句为:

Query query=session.createQuery(HQL语句);

1.5 Transaction:事务管理器

Transaction是Hibernate的数据库事务管理器,它对底层的事务做了封装,底层事务包括JDBC事务和JTA事务

try{    Transaction tran=session.beginTransaction();    ...    tran.commit();}catch(Exception e){    e.printStackTrace();    tran.rollback();}

2、实例:学生Student和班级Clazz,双向一对多关系

2.1 导入Hibernate必需jar包

2.2 Hibernate配置文件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"><hibernate-configuration> <session-factory>     <!--jdbc驱动,此处使用的数据库为sqlserver-->       <property name="hibernate.connection.driver_class">          com.microsoft.sqlserver.jdbc.SQLServerDriver       </property>      <property name="hibernate.connection.password">      </property>       <property name="hibernate.connection.url">           jdbc:sqlserver://127.0.0.1:1433;DatabaseName=数据库名字       </property>      <property name="hibernate.connection.username">           sa       </property>        <!--数据库方言-->      <property name="hibernate.dialect">            org.hibernate.dialect.SQLServerDialect     </property>    <!--根据映射文件自动创建数据库表格-->     <property name="hbm2ddl.auto">         create     </property>    <mapping resource="com/po/Student.hbm.xml" />                <mapping resource="com/po/Clazz.hbm.xml" />             </session-factory></hibernate-configuration>

2.3 创建session的公共类

//HibernateServiceProvider.javaimport org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateServiceProvider {    private static SessionFactory sessionFactory=null;    private static Configuration configuration=new Configuration();    public HibernateServiceProvider()    {        this.initHibernate();    }    public synchronized void initHibernate()    {        if(sessionFactory==null)        {            try            {                configuration.configure();                sessionFactory=configuration.buildSessionFactory();            }            catch(Exception e)            {                e.printStackTrace();            }        }    }    public void rebuildSessionFactory()    {        try        {            configuration.configure();            sessionFactory=configuration.buildSessionFactory();        }        catch(Exception e)        {            e.printStackTrace();        }    }    public Session getSession()    {        if(sessionFactory==null)        {            this.rebuildSessionFactory();        }        Session session=sessionFactory.openSession();        return session;    }    public void closeSession()    {        try        {            sessionFactory.close();        }        catch(Exception e)        {            e.printStackTrace();        }    }}

2.4 PO类和映射文件的编写

//Clazz.javaimport java.util.HashSet;import java.util.Set;public class Clazz {    private long claId;    private String claName;    private Set<Student> students=new HashSet<Student>();    public long getClaId() {        return claId;    }    public void setClaId(long claId) {        this.claId = claId;    }    public String getClaName() {        return claName;    }    public void setClaName(String claName) {        this.claName = claName;    }    public Set<Student> getStudents() {        return students;    }    public void setStudents(Set<Student> students) {        this.students = students;    }}//映射文件Clazz.hbm.xml,与po类放于同一目录下<?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"><hibernate-mapping>    <class name="com.po.Clazz" table="Clazz">        <id name="claId" type="long">            <column name="lClaId"/>            <generator class="native"/>        </id>        <property name="claName" type="java.lang.String">            <column name="vClaName" length="20"/>        </property>        <set name="students" table="Student" lazy="true" cascade="all">            <key>                <column name="lClaId"/>            </key>            <one-to-many class="com.po.Student"/>        </set>    </class></hibernate-mapping>

//Student.javapublic class Student {    private long stuId;    private String stuName;    private Clazz stuCla;    public long getStuId() {        return stuId;    }    public void setStuId(long stuId) {        this.stuId = stuId;    }    public String getStuName() {        return stuName;    }    public void setStuName(String stuName) {        this.stuName = stuName;    }    public Clazz getStuCla() {        return stuCla;    }    public void setStuCla(Clazz stuCla) {        this.stuCla = stuCla;    }}//映射文件Student.hbm.xml,与对应po类放于同一目录下<?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"><hibernate-mapping>    <class name="com.po.Student" table="Student">        <id name="stuId" type="long">            <column name="lStuId"/>            <generator class="native"/>        </id>        <property name="stuName" type="java.lang.String">            <column name="vStuName" length="20"/>        </property>        <many-to-one name="stuCla" class="com.po.Clazz" fetch="join" cascade="all">            <column name="lClaId"/>        </many-to-one>    </class></hibernate-mapping>

2.5 Dao类的编写

//ClazzDao.javaimport org.hibernate.Session;import org.hibernate.Transaction;import com.po.Clazz;public class ClazzDao {    HibernateServiceProvider hsProvider=new HibernateServiceProvider();    public boolean addClass(Clazz clazz)    {        boolean flag=false;        Session session=hsProvider.getSession();        Transaction trans=null;        try        {            trans=session.beginTransaction();            session.save(clazz);            trans.commit();            flag=true;        }        catch(Exception e)        {            e.printStackTrace();            trans.rollback();        }        return flag;    }}

省略其他Dao类

0 0