Hibernate学习之使用实例

下载

下载方式各异,有人喜欢直接自己来下需要的包,也有人使用MAVEN,还有人喜欢直接下Hibernate,然后解压,找到里面的lib文件夹,里面包括了使用Hibernate的依赖包。本人使用的是最后一种。如果使用第一种,可能会遇到缺少各种包的情况,附录中列出了一些包的下载地址。
下载地址:
http://nchc.dl.sourceforge.net/project/hibernate/hibernate4/4.3.10.Final/hibernate-release-4.3.10.Final.tgz

Build Path

下载后,找到lib文件夹下的required文件夹,然后把这个文件夹下的jar包都放到项目里的lib文件夹下,然后再 Build Path加入jar包引用。

MySQL

我用到的数据库是MySQL,数据库名为forconsumer,表名是seed。表的结构如下:

mysql> show columns from seed;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| seed_id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| seed_site    | varchar(200) | YES  |     | NULL    |                |
| seed_proid   | varchar(32)  | YES  |     | NULL    |                |
| seed_is_used | tinyint(4)   | YES  |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

构建实体类

package model;

/**
 * 种子表Seed类 - -
 * 此类规则:
 * 1、此类也称为POJO类,不能继承任何类,也不实现任何接口
 * 2、要有一个默认构造器
 * 3、有getXXX和setXXX方法,属性均为private
 * @author young
 *
 */
public class Seed {

    private int seed_id;
    private String seed_site;
    private String seed_proid;
    private byte seed_is_used; //byte对应MySQL里的TINYINT数据类型

    public Seed(){}

    public Seed(String seed_site, String seed_proid, byte seed_is_used){
        this.seed_site = seed_site;
        this.seed_proid = seed_proid;
        this.seed_is_used = seed_is_used;
    }

    public int getSeed_id(){
        return this.seed_id;
    }

    public void setSeed_id(int seed_id){
        this.seed_id = seed_id;
    }

    public String getSeed_site(){
        return this.seed_site;
    }

    public void setSeed_site(String seed_site){
        this.seed_site = seed_site;
    }

    public String getSeed_proid(){
        return this.seed_proid;
    }

    public void setSeed_proid(String seed_proid){
        this .seed_proid =  seed_proid;
    }

    public byte getSeed_is_used(){
        return this.seed_is_used;
    }

    public void setSeed_is_used(byte seed_is_used){
        this.seed_is_used = seed_is_used;
    }
}

操作数据库类

package dbhelper;

import java.util.Iterator;
import java.util.List;

import model.Seed;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class ManageSeed {

    private static SessionFactory factory = null; 

    static {
        factory =  new Configuration().configure().buildSessionFactory();
    }


    /**
     * 
     * @param seed
     * @return
     */
    public Integer addSeed(Seed seed){
        Session session = factory.openSession();
        Transaction ts = null ;
        Integer id = null ;
        try{
            ts = session.beginTransaction();
            id = (Integer) session.save(seed);
            ts.commit();
        }
        catch(HibernateException he){
            if(ts != null)
                ts.rollback();
            he.printStackTrace();
        }
        finally{
            session.close();
        }
        return id;
    }

    public void listSeed(){
        Session session = factory.openSession();
        Transaction ts = null;
        try{
            ts = session.beginTransaction();
            List  lstSeed = session.createQuery(" From Seed ").list();
            for(Iterator itr = lstSeed.iterator();itr.hasNext();){
                Seed seed = (Seed) itr.next();
                System.out.println("------------------------");
                System.out.println(" seed_id : " + seed.getSeed_id());
                System.out.println(" seed_site: " + seed.getSeed_site());
                System.out.println(" seed_proid: " + seed.getSeed_proid());
                System.out.println(" seed_is_used: " + seed.getSeed_is_used());
            }
            ts.commit();
        }
        catch(HibernateException he){
            if( ts != null)
                ts.rollback();
            he.printStackTrace();
        }
        finally{
            session.close();
        }
    }
}

重要的配置文件

hibernate.cfg.xml配置如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   <!-- MySQL对应的 hibernate.dialect是org.hibernate.dialect.MySQLDialect 
   不同类型的数据库对应不同的Dialect -->
   <property name="hibernate.dialect">
      org.hibernate.dialect.MySQLDialect
   </property>
   <property name="hibernate.connection.driver_class">
      com.mysql.jdbc.Driver
   </property>

   <!-- 配置连接URL,forconsumer是数据库的名字 -->
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/forconsumer
   </property>
   <property name="hibernate.connection.username">
      root
   </property>
   <property name="hibernate.connection.password">
      *****(此处直接填密码)
   </property>

   <!-- XML mapping files 列表 -->
   <!-- 种子表Seed -->
   <mapping resource="Seed.hbm.xml"/> 
   <!-- 产品表Product -->
   <!--  <mapping resource="Product.hbm.xml"/> -->

</session-factory>
</hibernate-configuration>

Seed.hbm.xml配置如下:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <!-- 这里的name要写全称,即包括包名,否则会提示找不到类 -->
   <class name="model.Seed" table="seed">
      <!-- 元数据,介绍类的相关信息 -->
      <meta attribute="class-description">
         This class contains the seed detail. 
      </meta>
      <id name="seed_id" type="int" column="seed_id">
         <!-- generator 指示此字段自动增长 -->
         <generator class="native"/>
      </id>
      <!-- name表示类中的属性,column表示在数据库中的字段名,type为数据类型 -->
      <property name="seed_site" column="seed_site" type="string"/>
      <property name="seed_proid" column="seed_proid" type="string"/>
      <property name="seed_is_used" column="seed_is_used" type="byte"/>
   </class>
</hibernate-mapping>

总结:首先,Hibernate真的很强大,很实用,也比较简单,最重要的几个部分为:配置文件和POJO类。还有一个比较容易犯的错就是,如果表名首字母是小写字母,在创建查询的时候,很容易写成” from seed “,这样的话,就会出现异常1的情况。

异常

异常1

INFO: HHH000397: Using ASTQueryTranslatorFactory
org.hibernate.hql.internal.ast.QuerySyntaxException: seed is not mapped [ From seed ]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:96)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:131)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:93)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1836)
    at dbhelper.ManageSeed.listSeed(ManageSeed.java:53)
    at main.Main.main(Main.java:36)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: seed is not mapped
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)
    at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:95)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:338)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3678)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3567)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:708)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:564)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
    ... 9 more

解决方法

我的查询语句是:
List lstSeed = session.createQuery(” From seed “).list();
虽然我的表名是seed,首字母小写,但在这里,必须写成Seed,即首字母大写。这是因为,此处的查询语句与我们平时用的SQL是不一样的,Hibernate有自己的HQL,这里的From Seed中的Seed是指类,而非SQL中的表,这条语句是说:返回所有Seed类的实例,而非从Seed表中查询数据。当然也支持在Hibernate中使用SQL,只是换个方法调用,例如:session.createSQLQuery(“SELECT * FROM CATS”).list();

异常2

Exception in thread “main” java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/ReflectionManager

解决方法

加入hibernate-commons-annotations.jar

异常3

Exception in thread “main” java.lang.NoClassDefFoundError: org/jboss/logging/BasicLogger

解决方法

加入jboss-logging.jar

异常4

Exception in thread “main” java.lang.NoClassDefFoundError: javax/transaction/SystemException

解决方法

加入jta.jar

附录

hibernate-core.jar
下载地址:
http://search.maven.org/remotecontent?filepath=org/hibernate/hibernate-core/4.3.10.Final/hibernate-core-4.3.10.Final.jar

dom4j.jar
http://search.maven.org/remotecontent?filepath=org/dom4j/dom4j/2.0.0-RC1/dom4j-2.0.0-RC1.jar
xalan.jar
http://search.maven.org/remotecontent?filepath=xalan/xalan/2.7.2/xalan-2.7.2.jar
xerces.jar
http://search.maven.org/remotecontent?filepath=xerces/xerces/2.4.0/xerces-2.4.0.jar
commons-logging.jar
http://search.maven.org/remotecontent?filepath=commons-logging/commons-logging/1.2/commons-logging-1.2.jar
hibernate-commons-annotations.jar
http://search.maven.org/remotecontent?filepath=org/hibernate/common/hibernate-commons-annotations/5.0.0.Final/hibernate-commons-annotations-5.0.0.Final.jar
jboss-logging.jar
http://search.maven.org/remotecontent?filepath=org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar
jta.jar
http://search.maven.org/remotecontent?filepath=javax/transaction/jta/1.1/jta-1.1.jar
hibernate-jpa.jar
http://search.maven.org/remotecontent?filepath=org/hibernate/javax/persistence/hibernate-jpa-2.0-api/1.0.1.Final/hibernate-jpa-2.0-api-1.0.1.Final.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值