最好将hibernate.cfg.xml文件存放于项目的根目录下。 4)生成.hbm.xml文件。File->New->Other->Hibernate->Hibernate Mapping File,出现如下界面: 在填写完Password后,点击Refresh按钮,就会在Tables中列出所有可以访问的数据库表,然后选中要为其生成.hbm.xml文件的表,点击Finish,即会生成对应的.hbm.xml文件,比如我上面选择的是Mobileuser表,就会生成Mobileuser.hbm.xml文件。(5)从.hbm.xml文件自动生成实体类。 在Package Explorer中选中Mobileuser.hbm.xml文件,右键->Hibernate Synchronizer->Synchronize Files ,即可生成对应的实体类和DAO类。如果你仅仅想要实体类,那么可以在Project->Properies->Hibernate Synchronizer->Data Access Objects ,将“I would like to have DAOs created for me”的钩选项去掉即可。(6)在hibernate.cfg.xml文件中添加对应的mapping resource。 在Package Explorer中选中Mobileuser.hbm.xml文件,右键->Hibernate Synchronizer->Add Mapping Reference,即会在hibernate.cfg.xml中自动生成如下配置:
< mapping resource = " HibernateTest/Mobileuser.hbm.xml " />(7)修改自动生成的hibernate.cfg.xml文件。需要在hibernate.cfg.xml文件的首部添加:
<! DOCTYPE hibernate - configuration PUBLIC " -//Hibernate/Hibernate Configuration DTD 3.0//EN " " http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd " >比较繁琐的是,每次自动修改hibernate.cfg.xml文件后,都要重新添加这个xml片断。 万事具备,现在可以写个测试来检验一下了:
// 仅仅作为示例,没有进行异常处理 public static void main(String[] args) { Configuration cfg = new Configuration().configure() ; SessionFactory sFactory = cfg.buildSessionFactory() ; Session session = sFactory.openSession() ; Transaction tx = session.beginTransaction(); Mobileuser user = (Mobileuser)session.load(Mobileuser. class , new Integer( 2 )) ; String age = user.getMobilenumber() ; System. out .println(age) ; tx.commit(); session.close() ; }