java

位置:IT落伍者 >> java >> 浏览文章

精通Hibernate:第一个Hibernate应用


发布日期:2020年02月01日
 
精通Hibernate:第一个Hibernate应用

在Java应用中使用Hibernate的步骤

创建Hibernate的配置文件

创建持久化类

创建对象关系映射文件

通过Hibernate API编写访问数据库的代码

Helloapp应用的结构

)thiswidth=; height=>

Hibernate的配置文件(hibernateproperties)

    j>

    hibernatedialect=orghibernatedialectMySQLDialect

    nnectiondriver_class=commysqljdbcDriver

    nnectionurl=jdbc:mysql://localhost:/SAMPLEDB

    nnectionusername=root

    nnectionpassword=

    hibernateshow_sql=true

    创建持久化类Customer

    持久化类符合JavaBean的规范包含一些属性以及与之对应的getXXX()和setXXX()方法

    持久化类有一个id属性用来惟一标识Customer类的每个对象在面向对象术语中这个id属性被称为对象标识符(OIDObject Identifier)通常它都用整数表示

    Hibernate要求持久化类必须提供一个不带参数的默认构造方法

      j>

      packagemypack;

      importjavaioSerializable;

      importjavasqlDate;

      importjavasqlTimestamp;

      publicclassCustomerimplementsSerializable{

      privateLongid;

      privateStringname;

      privateStringemail;

      privateStringpassword;

      privateintphone;

      privateStringaddress;

      privatecharsex;

      privatebooleanmarried;

      privateStringdescription;

      privatebyte[]image;

      privateDatebirthday;

      privateTimestampregisteredTime;

      publicCustomer(){}

      publicLonggetId(){

      returnid;

      }

      privatevoidsetId(Longid){

      thisid=id;

      }

      publicStringgetName(){

      returnname;

      }

      publicvoidsetName(Stringname){

      thisname=name;

      }

      publicStringgetEmail(){

      returnemail;

      }

      publicvoidsetEmail(Stringemail){

      thisemail=email;

      }

      publicStringgetPassword(){

      returnpassword;

      }

      publicvoidsetPassword(Stringpassword){

      thispassword=password;

      }

      publicintgetPhone(){

      returnphone;

      }

      publicvoidsetPhone(intphone){

      thisphone=phone;

      }

      publicStringgetAddress(){

      returnaddress;

      }

      publicvoidsetAddress(Stringaddress){

      thisaddress=address;

      }

      publicchargetSex(){

      returnsex;

      }

      publicvoidsetSex(charsex){

      thissex=sex;

      }

      publicbooleanisMarried(){

      returnmarried;

      }

      publicvoidsetMarried(booleanmarried){

      thismarried=married;

      }

      publicStringgetDescription(){

      returndescription;

      }

      publicvoidsetDescription(Stringdescription){

      thisdescription=description;

      }

      publicbyte[]getImage(){

      returnthisimage;

      }

      publicvoidsetImage(byte[]image){

      thisimage=image;

      }

      publicDategetBirthday(){

      returnthisbirthday;

      }

      publicvoidsetBirthday(Datebirthday){

      thisbirthday=birthday;

      }

      publicTimestampgetRegisteredTime(){

      returnthisregisteredTime;

      }

      publicvoidsetRegisteredTime(TimestampregisteredTime){

      thisregisteredTime=registeredTime;

      }

      }

      注意

      getXXX()和setXXX()方法可以采用任意的访问级别他的命名规则必须符合特定的命名规则getset后面紧跟属性的名字并且属性名的首字母为大写如name属性的get方法为getName()

      如果持久化类的属性为boolean类型那么它的get方法名可以用get做前缀也可以用is做前缀

      创建数据库Schema

        j>

        dropdatabaseifexistsSAMPLEDB;

        createdatabaseSAMPLEDB;

        useSAMPLEDB;

        createtableCUSTOMERS(

        IDbigintnotnullprimarykey

        NAMEvarchar()notnull

        EMAILvarchar()notnull

        PASSWORDvarchar()notnull

        PHONEint

        ADDRESSvarchar()

        SEXchar()

        IS_MARRIEDbit

        DESCRIPTIONtext

        IMAGEblob

        BIRTHDAYdate

        REGISTERED_TIMEtimestamp

        );

        创建对象关系映射文件Customerhbmxml

          j>

          <?xmlversion=?>

          <!DOCTYPEhibernatemappingPUBLIC//Hibernate/HibernateMappingDTD//ENmappingdtd>

          <hibernatemapping>

          <classname=mypackCustomertable=CUSTOMERS>

          <idname=idcolumn=IDtype=long>

          <generatorclass=increment/>

          </id>

          <propertyname=namecolumn=NAMEtype=stringnotnull=true/>

          <propertyname=emailcolumn=EMAILtype=stringnotnull=true/>

          <propertyname=passwordcolumn=PASSWORDtype=stringnotnull=true/>

          <propertyname=phonecolumn=PHONEtype=int/>

          <propertyname=addresscolumn=ADDRESStype=string/>

          <propertyname=sexcolumn=SEXtype=character/>

          <propertyname=marriedcolumn=IS_MARRIEDtype=boolean/>

          <propertyname=descriptioncolumn=DESCRIPTIONtype=text/>

          <propertyname=imagecolumn=IMAGEtype=binary/>

          <propertyname=birthdaycolumn=BIRTHDAYtype=date/>

          <propertyname=registeredTimecolumn=REGISTERED_TIMEtype=timestamp/>

          </class>

          </hibernatemapping>

          <id>元素映射OID

          <generator>子元素用来设定标识符生成器Hibernate提供了提供了多种内置的实现

          image onmousewheel=javascript:return big(this) border= alt= src=http://imgeducitycn/img_///jpg width= onload=javascript:if(thiswidth>)thiswidth=; height=>

          <property>元素映射值类型属性

          name属性指定持久化类的属性的名字

          column属性指定与类的属性映射的表的字段名

          type属性指定Hibernate映射类型Hibernate映射类型是Java类型与SQL类型的桥梁

          image onmousewheel=javascript:return big(this) border= alt= src=http://imgeducitycn/img_///png width= onload=javascript:if(thiswidth>)thiswidth=; height=>

          采用XML文件来配置对象关系映射的优点

          Hibernate既不会渗透到上层域模型中也不会渗透到下层数据模型中

          软件开发人员可以独立设计域模型不必强迫遵守任何规范

          数据库设计人员可以独立设计数据模型不必强迫遵守任何规范

          对象关系映射不依赖于任何程序代码如果需要修改对象关系映射只需修改XML文件不需要修改任何程序提高了软件的灵活性并且使维护更加方便

          创建BusinessService类

          image onmousewheel=javascript:return big(this) border= alt= src=http://imgeducitycn/img_///png width= onload=javascript:if(thiswidth>)thiswidth=; height=>

            j>

            packagemypack;

            importjavaxservlet*;

            importorghibernate*;

            importorghibernatecfgConfiguration;

            importjavaio*;

            importjavasqlDate;

            importjavasqlTimestamp;

            importjavautil*;

            publicclassBusinessService{

            publicstaticSessionFactorysessionFactory;

            /**初始化Hibernate创建SessionFactory实例*/

            static{

            try{

            //根据默认位置的Hibernate配置文件的配置信息创建一个Configuration实例

            Configurationconfig=newConfiguration();

            //加载Customer类的对象关系映射文件

            configaddClass(Customerclass);

            //创建SessionFactory实例*/

            sessionFactory=configbuildSessionFactory();

            }catch(RuntimeExceptione){eprintStackTrace();throwe;}

            }

            /**查询所有的Customer对象然后调用printCustomer()方法打印Customer对象信息*/

            publicvoidfindAllCustomers(ServletContextcontextPrintWriterout)throwsException{

            Sessionsession=sessionFactoryopenSession();//创建一个会话

            Transactiontx=null;

            try{

            tx=sessionbeginTransaction();//开始一个事务

            Queryquery=sessioncreateQuery(fromCustomerascorderbycnameasc);

            Listcustomers=querylist();

            for(Iteratorit=erator();ithasNext();){

            printCustomer(contextout(Customer)itnext());

            }

            mit();//提交事务

            }catch(RuntimeExceptione){

            if(tx!=null){

            txrollback();

            }

            throwe;

            }finally{

            sessionclose();

            }

            }

            /**持久化一个Customer对象*/

            publicvoidsaveCustomer(Customercustomer){

            Sessionsession=sessionFactoryopenSession();

            Transactiontx=null;

            try{

            tx=sessionbeginTransaction();

            sessionsave(customer);

            mit();

            }catch(RuntimeExceptione){

            if(tx!=null){

            txrollback();

            }

            throwe;

            }finally{

            sessionclose();

            }

            }

            /**按照OID加载一个Customer对象然后修改它的属性*/

            publicvoidloadAndUpdateCustomer(Longcustomer_idStringaddress){

            Sessionsession=sessionFactoryopenSession();

            Transactiontx=null;

            try{

            tx=sessionbeginTransaction();

            Customerc=(Customer)sessionget(Customerclasscustomer_id);

            csetAddress(address);

            mit();

            }catch(RuntimeExceptione){

            if(tx!=null){

            txrollback();

            }

            throwe;

            }finally{

            sessionclose();

            }

            }

            /**删除Customer对象*/

            publicvoiddeleteCustomer(Customercustomer){

            Sessionsession=sessionFactoryopenSession();

            Transactiontx=null;

            try{

            tx=sessionbeginTransaction();

            sessiondelete(customer);

            mit();

            }catch(RuntimeExceptione){

            if(tx!=null){

            txrollback();

            }

            throwe;

            }finally{

            sessionclose();

            }

            }

            /**选择向控制台还是Web网页输出Customer对象的信息*/

            privatevoidprintCustomer(ServletContextcontextPrintWriteroutCustomercustomer)throwsException{

            if(context!=null)

            printCustomerInWeb(contextoutcustomer);

            else

            printCustomer(outcustomer);

            }

            /**把Customer对象的信息输出到控制台如DOS控制台*/

            privatevoidprintCustomer(PrintWriteroutCustomercustomer)throwsException{

            byte[]buffer=customergetImage();

            FileOutputStreamfout=newFileOutputStream(photo_copygif);

            foutwrite(buffer);

            foutclose();

            outprintln(以下是+customergetName()+的个人信息);

            outprintln(ID:+customergetId());

            outprintln(口令:+customergetPassword());

            outprintln(EMail:+customergetEmail());

            outprintln(电话:+customergetPhone());

            outprintln(地址:+customergetAddress());

            Stringsex=customergetSex()==M?:;

            outprintln(性别:+sex);

            StringmarriedStatus=customerisMarried()?已婚:未婚;

            outprintln(婚姻状况:+marriedStatus);

            outprintln(生日:+customergetBirthday());

            outprintln(注册时间:+customergetRegisteredTime());

            outprintln(自我介绍:+customergetDescription());

            }

            j>

            j>

            /**把Customer对象的信息输出到动态网页*/

            privatevoidprintCustomerInWeb(ServletContextcontextPrintWriteroutCustomercustomer)throwsException{

            //保存照片

            byte[]buffer=customergetImage();

            Stringpath=contextgetRealPath(/);

            FileOutputStreamfout=newFileOutputStream(path+photo_copygif);

            foutwrite(buffer);

            foutclose();

            outprintln(以下是+customergetName()+的个人信息+<br>);

            outprintln(ID:+customergetId()+<br>);

            outprintln(口令:+customergetPassword()+<br>);

            outprintln(EMail:+customergetEmail()+<br>);

            outprintln(电话:+customergetPhone()+<br>);

            outprintln(地址:+customergetAddress()+<br>);

            Stringsex=customergetSex()==M?:;

            outprintln(性别:+sex+<br>);

            StringmarriedStatus=customerisMarried()?已婚:未婚;

            outprintln(婚姻状况:+marriedStatus+<br>);

            outprintln(生日:+customergetBirthday()+<br>);

            outprintln(注册时间:+customergetRegisteredTime()+<br>);

            outprintln(自我介绍:+customergetDescription()+<br>);

            outprintln(<imgsrc=photo_copygifborder=><p>);

            }

            publicvoidtest(ServletContextcontextPrintWriterout)throwsException{

            Customercustomer=newCustomer();

            customersetName(Tom);

            customersetEmail();

            customersetPassword();

            customersetPhone();

            customersetAddress(Shanghai);

            customersetSex(M);

            customersetDescription(Iamveryhonest);

            //设置Customer对象的image属性它是字节数组存放photogif文件中的二进制数据

            //photogif文件和BusinessServiceclass文件位于同一个目录下

            InputStreamin=thisgetClass()getResourceAsStream(photogif);

            byte[]buffer=newbyte[inavailable()];

            inread(buffer);

            customersetImage(buffer);

            //设置Customer对象的birthday属性它是javasqlDate类型

            customersetBirthday(DatevalueOf());

            saveCustomer(customer);

            findAllCustomers(contextout);

            loadAndUpdateCustomer(customergetId()Beijing);

            findAllCustomers(contextout);

            deleteCustomer(customer);

            }

            publicstaticvoidmain(Stringargs[])throwsException{

            newBusinessService()test(nullnewPrintWriter(Systemouttrue));

            sessionFactoryclose();

            }

            }

            image onmousewheel=javascript:return big(this) border= alt= src=http://imgeducitycn/img_///png width= onload=javascript:if(thiswidth>)thiswidth=; height=>

            image onmousewheel=javascript:return big(this) border= alt= src=http://imgeducitycn/img_///png width= onload=javascript:if(thiswidth>)thiswidth=; height=>

            image onmousewheel=javascript:return big(this) border= alt= src=http://imgeducitycn/img_///png width= onload=javascript:if(thiswidth>)thiswidth=; height=>

            saveCustomer()方法

            该方法调用Session的save()方法把Customer对象持久化到数据库中

              j>

              tx=sessionbeginTransaction();

              sessionsave(customer);

              mit();

              当运行sessionsave()方法时Hibernate执行以下SQL语句

                j>

                insertintoCUSTOMERS(IDNAMEEMAILPASSWORDPHONEADDRESSSEX

                IS_MARRIEDDESCRIPTIONIMAGEBIRTHDAYREGISTERED_TIME)

                values(TomShanghaiMIamveryhonest&#;null)

                在test()方法中并没有设置Customer对象的id属性Hibernate会根据映射文件的配置采用increment标识符生成器自动以递增的方式为OID赋值在Customerhbmxml文件中相关的映射代码如下

                  j>

                  <idname=idcolumn=IDtype=long>

                  <generatorclass=increment/>

                  </id>

                  findAllCustomers()方法

                  该方法通过Query接口查询所有的Customer对象

                    j>

                    tx=sessionbeginTransaction();//开始一个事务

                    Queryquery=sessioncreateQuery(fromCustomerascorderbycnameasc);

                    Listcustomers=querylist();

                    for(Iteratorit=erator();ithasNext();){

                    printCustomer(contextout(Customer)itnext());

                    }

                    mit();//提交事务

                    Session的createQuery()方法的参数from Customer as c order by cname asc使用的是Hibernate查询语言运行Querylist()方法时 Hibernate执行以下SQL语句

                      j>

                      select*fromCUSTOMERSorderbyNAMEasc;

                      loadAndUpdateCustomer ()方法

                      该方法调用Session的get()方法加载Customer对象然后再修改Customer对象的属性

                        j>

                        tx=sessionbeginTransaction();

                        Customerc=(Customer)sessionget(Customerclasscustomer_id);

                        csetAddress(address);//修改内存中Customer对象的address属性

                        mit();

                        以上代码先调用Session的get()方法它按照参数指定的OID从数据库中检索出匹配的Customer对象Hibernate会执行以下SQL语句

                          j>

                          select*fromCUSTOMERSwhereID=;

                          loadAndUpdateCustomer()方法接着修改Customer对象的address属性那么Hibernate会不会同步更新数据库中相应的CUSTOMERS表的记录呢?答案是肯定的Hibernate采用髒检查机制按照内存中的Customer对象的状态的变化来同步更新数据库中相关的数据Hibernate会执行以下SQL语句

                            j>

                            updateCUSTOMERSsetNAME=TomEMAIL=…ADDRESS=Beijing

                            whereID=;

                            尽管只有Customer对象的address属性发生了变化但是Hibernate执行的update语句中会包含所有的字段

                            deleteCustomer()方法

                            该方法调用Session的delete()方法删除特定的Customer

                            对象

                              j>

                              tx=sessionbeginTransaction();

                              sessiondelete(customer);

                              mit();

                              运行sessiondelete()方法时Hibernate根据Customer对象的OID执行以下SQL delete语句

                                j>

                                deletefromCUSTOMERSwhereID=;&nbsp;

                                效果图

                                image onmousewheel=javascript:return big(this) border= alt= src=http://imgeducitycn/img_///png width= onload=javascript:if(thiswidth>)thiswidth=; height=>

               

上一篇:使用Struts2必须配备的Jar包

下一篇:Struts表单验证设计指南