Hibernate插件的安装及配置环境

一、安装方法说明(hibernatetools-4.1.1.Final):

(1)Help --> Install New Software

(2)Add -->Archive...找到已经下载好的hibernatetools-Update-4.1.1.Final_2013-12-08_01-06-33-B605.zip—>打开

(3)Navigate to hibernatetools-Update-4.1.1.Final_2013-12-08_01-06-33-B605.zip  and click  Open

(4)Clicking OK in the Add Site dialog will bring you back to the dialog 'Install'

(5)Select the Jboss Tools hibernatetools Nightly Build Update Site that has appeared

(6)Click Next  and then Finish
(7)Approve the license

(8)Restart eclipse when that is asked

二、配置环境

(1)导入Hibernate必须的jar包

找到hibernate-release-4.2.4.zip解压-lib-required中所有的jar包

(2)加入数据库驱动的jar包

(3)由插件自动生成配置文件

邮件src-new-other-选择hibernate-hibernate-cfg.xml

三、给hibernate的配置文件hibernate-cfg.xml关联dtd,实现自动提示

(1)复制由插件生成的配置文件中URI:以hibernate-configuration-3.0.dtd

(2)window-preference-xml catalog-add-keytype选择URI-key为复制的URI-file system

(3)找到hibernate-release-4.2.4.zip下-project-hibernate-core下-src-main-resources-org-hibernate-选择hibernate-configuration3.0.dtd-点击打开——OK——重新打开配置文件就有提示了

四、配置文件中常用的属性,比如hibernate方言的属性

hibernate-release-4.2.4.zip下-project-etc-hibernate.properties

五、hibernate的使用步骤

(1)用插件创建hibernate的配置文件hibernate.cfg.xml 

(2)创建持久化类

(3)创建对象-关系映射文件*.hbm.xml

src-包右键-new-other-hibernate-*.hbm.xml -一路下一步-OK

(4)通过hibernateAPI编写访问数据库的代码

 六、helloworld

hibernate中有3个非常重要的类:配置类(Configuration)、会话工厂类(SessionFactory)和会话类(Session)

//1、加载配置文件和对象关系映射信息,映射文件需要在配置文件中进行指定关联
Configuration cfg= new Configuration().configure();
//3、创建一个ServiceRegistry对象,hibernate的任何配置和服务都需要在该对象中注册之后才能生效,由于ServiceRegistry是一个接口,所以创建方式如下:
ServiceRegistryBuilder serviceRegistryBuilder= new ServiceRegistryBuilder().applySettings(cfg.getProperties()) //获取配置信息中的属性
  ServiceRegistry  serviceRegistry = serviceRegistryBuilder.buildServiceRegistry();              
//2、创建一个SessionFactory对象,保存当前数据库所有的映射关系
SessionFactory sf = cfg.buildSessionFactory(serviceRegistry);
//4、创建一个session对象,通过该对象可以实现数据库的增、删、改、查的操作
Session session =  sf.openSession();
//5、开启事务
Transaction transaction = session.beginTransaction();
//6、执行相关操作,比如保存操作,将student对象保存到对应的数据库中
Student stu = new Student("1","zhangsan","12");//分别有学号、姓名、年龄的属性
transaction.save(stu);
//7、提交事务
transaction.commit();
//8、关闭session
session.close();
//9、关闭sessionFactory
sf.close();

猜你喜欢

转载自zxq1007097830.iteye.com/blog/2380805
今日推荐