hibernate入门

作为新手刚学hibernate不久,发表一篇博客同时也为自己做做总结。

一、开始前准备三步骤:

1、导入hibernate所需要的jar包以及数据库连接包

2、配置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">


<hibernate-configuration>


<session-factory>
<property name="myeclipse.connection.profile">oracel</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/mathmodeling
</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="show_sql">true</property>
<mapping resource="com/ccsu/bean/News.hbm.xml" />
</session-factory>
</hibernate-configuration>

3建立实体类以及实体类映射文件(比如News类对应的文件News.hbm.xml)

<?xml version="1.0"?>
<!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 - Hibernate Tools
-->
<hibernate-mapping>
    <class name="com.ccsu.bean.News" table="news" catalog="mathmodeling">
        <id name="nid" type="java.lang.Integer">
            <column name="nid" />
           <generator class="identity" />
        </id>
        <property name="subject" type="string">
            <column name="subject" length="50" not-null="true" />
        </property>
        <property name="content" type="string">
            <column name="content" length="3000" not-null="true" />
        </property>
        <property name="display" type="java.lang.Boolean">
            <column name="display" length="3" not-null="true" />
        </property>
        <property name="createTime" type="timestamp">
            <column name="createTime" length="20" not-null="true" />
        </property>
        <property name="updateTime" type="timestamp">
            <column name="updateTime" length="20" />
        </property>
        <property name="type" type="java.lang.Integer">
            <column name="type" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

二、使用hibernate的七个步骤

1、读取配置文件

Configuration conf = new Configuration().config();

2、创建sessionFactory

SessionFactory sf = conf.buildSessionFactory();

3打开session

Session session = sf.openSession();

4开启事物

Transaction tx = session.beginTransaction();

5经行数据操作

News news =new News();

....

session.save(news);

6提交事物

tx.commit()

7最为重要的不能忘记关闭连接

session.close();


三hibernate的查询

1HQL语句查询

编写HQL语句 String hql =“select news from News(千万记住是类名) news  where news.content like '啊哈'”

得到Query    Query query = session.createQuery(hql );

执行查询得到结果  List list = query.list();


2Criteria查询

Criteria c = session.createCriteria(类.class);

你可能感兴趣的:(hibernate入门)