hibernate初使用

准备工作,安装及配置Hibernate

http://zhoualine.iteye.com/blog/1190141

产生数据库表映射 Java 对象时,我增加了数据库中的两张表分别为Chatlog和Users

 

 

准备工作完了之后,在项目中新建一个类PrjData.java,主要是为了配置项目的SessionFactory

public class PrjData {
    /**
     * 整个项目的sessionfactory
     */
    private static SessionFactory sessionFactory = null;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure();
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                    .applySettings(configuration.getProperties())
                    .buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            Logs.error(e.toString());
        }
    }
    
    /**
     * 静态函数,用于加载配置文件获取session对象
     * 
     * @return Session
     */
    public static Session getSession() // 获取session对象
    {
        return sessionFactory.openSession();
    }
}

配置参考:http://www.cnblogs.com/liuyang-1037/archive/2009/03/26/1422254.html

 

接下来就是测试我们通过Hibernate与数据库的交互情况了

public static void testInsert() {
    String[] contents = new String[] { "今天", "人生赢家", "我爱你"};

    Session session = PrjData.getSession();
    Transaction transaction = session.beginTransaction();

    for(int i = 0; i < contents.length; i ++) {
        Chatlog chatlog = new Chatlog();

        chatlog.setContent(contents[i]);

        if(null != session) {
            session.save(chatlog);
        }
    }

    try {
        session.flush();
        transaction.commit();
        session.close();
    } catch (Exception e) {
        Logs.error(e.toString());
        e.printStackTrace();
        // TODO: 异常抛出后如何处理
        session.close();
        return ;
    }
}

public static void main(String[] args) {
    testInsert();
}

在此过程中我一共遇到了一下异常

1.org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver org.gjt.mm.mysql.Driver could not be loaded

   这是因为在忘记在路径中配置mysqlconnecter这个jar包,配置下就解决问题了

2.org.hibernate.MappingNotFoundException: resource: Chatlog.hbm.xml not found

  这个问题是因为我们在生成一个hibernate.cfg.xml后没有将我们加入的其他hbm.xml文件映射进来,所以找不到,在hibernate.cfg.xml中添加如下代码既可

<mapping resource = "com/italk/hibernate/Chatlog.hbm.xml"/>
<mapping resource = "com/italk/hibernate/Users.hbm.xml"/>

  注意其中的“/”不要习惯的换成“.”

3.org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

  在网上查询后有的是因为model类没有写好setter和getter方法,但是我的两个model都是自动生成的,没问题,经过检查发现原来是导入的jar包不正确,重新导入需要的jar后     问题就解决了,参考http://blog.csdn.net/myloveyoyo1314/article/details/4445644

 

问题解决完后编译程序,查看数据库,没问题!

 

接下来就是尝试在hbm.xml中加入自己的sql语句了

使用原声sql查询<sql_query>,使用这种方式必须要把所有的列写全才行,否则会报“列名无效”的错误,除非使用return-scalar来设置字段类型

1.不带参数的查询

<sql-query name="getChatlogs"><![CDATA[select j.* from Chatlog as j limit 10]]>
        <return alias="j" class="com.italk.hibernate.Chatlog"></return>
    </sql-query>
public List<Chatlog> getChatlogs() {
        Session session = PrjData.getSession();
        Query query = session.getNamedQuery("getChatlogs"); 
        List<Chatlog> list = query.list();
        session.close();
        
        return list;
    }

 

2.带参数查询

<sql-query name="getChatlog">
        <![CDATA[select j.* from Chatlog as j where j.content=:theContent and j.parentID=:theParentID]]>
        <return alias="j" class="com.italk.hibernate.Chatlog"></return>
    </sql-query>
/**
     * 根据content和parentID从数据库中获得一个Chatlog
     * 
     * @param content 
     * @param parentID
     * @return 返回数据中匹配的CHatlog 否则返回null
     */
    public Chatlog getChatlog(String content, long parentID) {
        Session session = PrjData.getSession();
        Query query = session.getNamedQuery("getChatlog"); 
        query.setString("theContent", content);
        query.setLong("theParentID", parentID);
        List<Chatlog> list = query.list();
        session.close();
        
        if(null != list && 0 != list.size())
            return list.get(0);
        return null;
        
    }

 

3.带返回类型查询

<sql-query name="getRecirdsCount"><return-scalar column="num" type="long"/><![CDATA[SELECT COUNT(*) as num FROM chat_record]]>
    </sql-query>
public static void getRecordCount() {
        Session session = PrjData.getSession();
        Query query = session.getNamedQuery("getRecirdsCount"); // 按更新时间和顶人数执行查询语句,在ChatRecords.hbm.xml文件中声明
        List<?> list = query.list();
        session.close();
        int size = list.size();

        long count= (Long) list.get(0);
    }

 

到此,我的Hibernate初体验基本结束,欢迎多多指正。

posted @ 2013-11-26 23:45  kkrimen  阅读(1270)  评论(0编辑  收藏  举报