|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
C#是盗用了Java的源代码,仿照开发的,原因是Java是开源的啊,盗了也白盗,还有一点,开发C#语言的团队是就是开发Java语言的团队,是微软重金挖过去的啊这篇文章次要说的是在Hibernate中的组件(Component)映照,能够参考Hibernate官方文档的第7章。至于情况设置,能够参考这个系列的后面几篇文章。1.创立项目·新建一个Java项目:ComponentMapping,注重选中“创立独自的源文件夹和输入文件夹”,同时增加“用户库”:hibernate。2.编写类文件·新建一个类,包名:javamxj.hibernate.component,类名:Person。
Person.java
/**Hibernate-组件(Component)映照*创立日期2005-4-10*@authorjavamxj(分享java康乐)*@linkBlog:htpp://javamxj.mblogger.cn*htpp://blog.csdn.net/javamxj/*/packagejavamxj.hibernate.component;/***@hibernate.class*/publicclassPerson{privateLongid;privateStringusername;privateAddressaddress;/***@hibernate.id*generator-class="hilo"*unsaved-value="null"*/publicLonggetId(){returnid;}publicvoidsetId(Longid){this.id=id;}/***@hibernate.property*length="15"*unique="true"*not-null="true"*/publicStringgetUsername(){returnusername;}publicvoidsetUsername(Stringusername){this.username=username;}/***@hibernate.component*/publicAddressgetAddress(){returnaddress;}publicvoidsetAddress(Addressaddress){this.address=address;}}
·Person类挪用了Address类,注重在“getAddress()”办法上的“@hibernate.component”标志。·Address类只含有一些“@hibernate.property”标志,未将其自力映照为一个表。
Address.java
packagejavamxj.hibernate.component;publicclassAddress{privateStringcountry;privateStringcity;privateStringstreet;privateStringzipCode;publicAddress(){}publicAddress(Stringcountry,Stringcity,Stringstreet,Stringzipcode){super();this.country=country;this.city=city;this.street=street;this.zipCode=zipcode;}/***@hibernate.property*length="12"*/publicStringgetCity(){returncity;}publicvoidsetCity(Stringcity){this.city=city;}/***@hibernate.property*length="12"*/publicStringgetCountry(){returncountry;}publicvoidsetCountry(Stringcountry){this.country=country;}/***@hibernate.property*length="6"*/publicStringgetZipCode(){returnzipCode;}publicvoidsetZipCode(Stringnumber){this.zipCode=number;}/***@hibernate.property*length="12"*/publicStringgetStreet(){returnstreet;}publicvoidsetStreet(Stringstreet){this.street=street;}publicStringtoString(){return("寓居在"+country+city+"市"+street+"区"+"
邮政编码:"+zipCode);}}
3.运转义务·复制《Eclipse疾速上手Hibernate--4.承继映照(1)》文中的build.xml到项目目次下。·双击“generate-hbm”义务,会发明在包中多了一个Animal.hbm.xml文件,在src目次下会多了一个hibernate.cfg.xml文件,假如没有,按F5键革新一下。
Person.hbm.xml
<?xmlversion="1.0"encoding="GBK"?><!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD2.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"><hibernate-mapping><classname="javamxj.hibernate.component.Person"dynamic-update="false"dynamic-insert="false"select-before-update="false"optimistic-lock="version"><idname="id"column="id"type="java.lang.Long"unsaved-value="null"><generatorclass="hilo"><!--ToaddnonXDocletgeneratorparameters,createafilenamedhibernate-generator-params-Person.xmlcontainingtheadditionalparametersandplaceitinyourmergedir.--></generator></id><propertyname="username"type="java.lang.String"update="true"insert="true"access="property"column="username"length="15"not-null="true"unique="true"/><componentname="address"class="javamxj.hibernate.component.Address"><propertyname="city"type="java.lang.String"update="true"insert="true"access="property"column="city"length="12"/><propertyname="country"type="java.lang.String"update="true"insert="true"access="property"column="country"length="12"/><propertyname="zipCode"type="java.lang.String"update="true"insert="true"access="property"column="zipCode"length="6"/><propertyname="street"type="java.lang.String"update="true"insert="true"access="property"column="street"length="12"/></component><!--ToaddnonXDocletpropertymappings,createafilenamedhibernate-properties-Person.xmlcontainingtheadditionalpropertiesandplaceitinyourmergedir.--></class></hibernate-mapping>
·运转MySql服务器,然后双击“schemaexport”义务,在项目根目次下,会发生一个“schema-export.sql”文件。schema-export.sql
droptableifexistsPersondroptableifexistshibernate_unique_keycreatetablePerson(idbigintnotnull,usernamevarchar(15)notnullunique,cityvarchar(12),countryvarchar(12),zipCodevarchar(6),streetvarchar(12),primarykey(id))createtablehibernate_unique_key(next_hiinteger)insertintohibernate_unique_keyvalues(0)
·切换到数据库中,会发明已主动发生了数据表Person5.测试程序●这一次分歧于后面的几个实例,此次先完成一个HibernateUtil帮助类,用来办理Hibernate的Session,如许测试类的代码就对照复杂了,能够参考Hibernate官方文档的第1章。·新建一个类,包名:javamxj.hibernate.util,类名:HibernateUtil,代码以下:
HibernateUtil.java
packagejavamxj.hibernate.util;importorg.apache.commons.logging.Log;importorg.apache.commons.logging.LogFactory;importnet.sf.hibernate.HibernateException;importnet.sf.hibernate.Session;importnet.sf.hibernate.SessionFactory;importnet.sf.hibernate.Transaction;importnet.sf.hibernate.cfg.Configuration;publicclassHibernateUtil{privatestaticLoglog=LogFactory.getLog(HibernateUtil.class);privatestaticSessionFactorysessionFactory;privatestaticfinalThreadLocalthreadSession=newThreadLocal();privatestaticfinalThreadLocalthreadTransaction=newThreadLocal();publicstaticSessionFactorygetSessionFactory(){if(sessionFactory==null){try{//CreatetheSessionFactorysessionFactory=newConfiguration().configure().buildSessionFactory();}catch(HibernateExceptionex){ex.printStackTrace();thrownewRuntimeException("Configurationproblem:"+ex.getMessage(),ex);}}returnsessionFactory;}publicstaticSessioncurrentSession()throwsHibernateException{Sessions=(Session)threadSession.get();//OpenanewSession,ifthisThreadhasnoneyetif(s==null){s=getSessionFactory().openSession();log.debug("###OpeningnewSessionforthisthread:"+s);threadSession.set(s);}else{log.debug("###Sessionwasexisted:"+s);}returns;}publicstaticvoidcloseSession()throwsHibernateException{Sessions=(Session)threadSession.get();threadSession.set(null);if(s!=null){log.debug("###ClosingSessionofthisthread."+s);s.close();}}publicstaticvoidbeginTransaction()throwsHibernateException{Transactiontx=(Transaction)threadTransaction.get();try{if(tx==null){tx=currentSession().beginTransaction();log.debug("###Startingnewdatabasetransactioninthisthread:"+tx);threadTransaction.set(tx);}else{log.debug("###Txwasexisted:"+tx);}}catch(HibernateExceptionex){throwex;}}publicstaticvoidcommitTransaction()throwsHibernateException{Transactiontx=(Transaction)threadTransaction.get();try{if(tx!=null&&!tx.wasCommitted()&&!tx.wasRolledBack()){log.debug("###Committingdatabasetransactionofthisthread.");tx.commit();}threadTransaction.set(null);}catch(HibernateExceptionex){rollbackTransaction();throwex;}}publicstaticvoidrollbackTransaction()throwsHibernateException{Transactiontx=(Transaction)threadTransaction.get();try{threadTransaction.set(null);if(tx!=null&&!tx.wasCommitted()&&!tx.wasRolledBack()){log.debug("###Tyringtorollbackdatabasetransactionofthisthread.");tx.rollback();}}catch(HibernateExceptionex){throwex;}finally{closeSession();}}}
·好了,然后在包javamxj.hibernate.component下新建一个ComponentDemo.java类。
ComponentDemo.java
packagejavamxj.hibernate.component;importjava.util.Iterator;importjava.util.List;importjavamxj.hibernate.util.HibernateUtil;importnet.sf.hibernate.HibernateException;importnet.sf.hibernate.Session;publicclassComponentDemo{publicstaticvoidmain(String[]args){try{newComponentDemo();}catch(HibernateExceptionhe){he.printStackTrace();}}publicComponentDemo()throwsHibernateException{Sessionsess=HibernateUtil.currentSession();Personp=newPerson();p.setAddress(newAddress("中国","上海","普陀","200055"));p.setUsername("JavaMXJ");sess.save(p);p=newPerson();p.setAddress(newAddress("中国","北京","海淀","100086"));p.setUsername("张三");sess.save(p);Listanimals=sess.find("from"+Person.class.getName());for(Iteratorit=animals.iterator();it.hasNext();){Personperson=(Person)it.next();System.out.println(person.getUsername()+":"+person.getAddress());}HibernateUtil.closeSession();}}
·运转这个类,把持台输入以下:·同时,数据表中天生以下数据:·最初的项目布局以下:
主要缺点就是:速度比较慢,没有C和C++快 |
|