在eclipse中使用hibernate和QBC及注意事项-mysql篇

来源:互联网 发布:淘宝月销量可以造假吗 编辑:程序博客网 时间:2024/05/22 08:08

我的环境:eclipse 3.6.2-helios+mysql5。hibernate在eclipse中的安装可以参考我的这篇博客:http://blog.csdn.net/nkliming/article/details/7865209。鼓捣了一个下午,终于把各种奇葩的问题给解决了,这里我总结了以下几个问题:

1.首先要保证目录结构的正确性。在反向工程中生成的hibernate.cfg.xml和hibernate.reveng.xml要保证在src目录下,否则会出现找不到xml文件的错误。

2.导包问题。选择build path->configure build path后,选择add external jars,将“%eclipse安装目录%\plugins\org.hibernate.eclipse_3.4.1.v20111025-0625-H210-Final\lib\hibernate”目录下的所有包都导入进来。

3.对hibernate.cfg.xml中做以下配置:比如<mapping resource="com/rbac/shop/model/Backorderinfo.hbm.xml"/>,将*.hbm.xml都添加到mapping中,否则会报找不到entity的错误。添加这样一个property:

<property name="hibernate.current_session_context_class">jta</property>(在集成Hibernate的环境下、例如Jboss),或者

<property name="current_session_context_class">thread</property> ( 在不集成Hibernate的环境下、例如使用JDBC的独立应用程序)

在这里,我使用的jboss集成hibernate环境,所以添加的是上面一句。

4.需要导入mysql-connector.jar,导入方法跟2里提到的一样。

5.修改*.hbm.xml中的内容,默认情况下:<class name="com.rbac.shop.model.Backorderinfo" table="backorderinfo" catalog="crmerpdb">。但是实际运行会发现报各种各样的错误HibernateException,主要原因是默认情况下多加了一个catalog属性,只要把这个属性删掉就可以了。如果使用了级联,注意将相应的lazy属性设置为false。

6.在dao层,也就是与数据库的交互层中,可以参考以下代码书写QBC查询:

public static Productinfo getProductinfoByName(final String name){Configuration cfg=new Configuration();cfg=cfg.configure();Session session = cfg.buildSessionFactory().openSession();try {Criteria criteria=session.createCriteria(Productinfo.class);criteria.add(Restrictions.eq("productname", name));List<Productinfo> list=criteria.list();if(list.isEmpty()){return null;}else {return list.get(0);}} catch (Exception e) {e.printStackTrace();session.getTransaction().rollback();return null;} finally{session.close();}}

public static boolean saveOrUpdateProduct(final Productinfo productinfo){Configuration cfg=new Configuration();cfg=cfg.configure();Session session = cfg.buildSessionFactory().openSession();try {session.beginTransaction();session.saveOrUpdate(productinfo);session.getTransaction().commit();return true;} catch (Exception e) {e.printStackTrace();session.getTransaction().rollback();return false;} finally{session.close();}}

需要注意前三行代码,这是我查阅各种资料后总结出来的可以运行的session创立方式。

7.对于懒加载的设置,注意,无论是one-to-many还是many-to-one,都要设置成lazy=false,因为这两个分别对应于级联的存取,两个操作均需要lazy=false的设置,请看下面两个代码段:

<set name="privilegeinfos" table="privilegeinfo" inverse="true" lazy="false" fetch="select">            <key>                <column name="roleId" />            </key>            <one-to-many class="com.rbac.shop.model.Privilegeinfo" />        </set>
        <many-to-one name="privilegeinfo" class="com.rbac.shop.model.Privilegeinfo" fetch="select" lazy="false">            <column name="privilegeId" />        </many-to-one>

8.还要注意一个问题就是Data source rejected establishment of connection, message from server:Too many connections,解决方案可以参考这篇博客:

http://blog.csdn.net/chenzhang8/article/details/6411570

ps:由于时间关系,只是粗略地总结,希望对大家有所帮助,如果有不足或错误之处,还请指正,谢谢!