《精通Hibernate》学习(1) 《精通Hibernate》学习(1)——第一个Hibernate应用
转自:http://blog.****.net/yu422560654/article/details/7028748
一、在Java应用中使用Hibernate的步骤
- 创建Hibernate的配置文件
- 创建持久化类
- 创建对象-关系映射文件
- 通过Hibernate API编写访问数据库的代码
二、Helloapp应用的结构
三、Hibernate的配置文件(hibernate.properties)
- hibernate.dialect=org.hibernate.dialect.MySQLDialect
- hibernate.connection.driver_class=com.mysql.jdbc.Driver
- hibernate.connection.url=jdbc:mysql://localhost:3306/SAMPLEDB
- hibernate.connection.username=root
- hibernate.connection.password=1234
- hibernate.show_sql=true
四、创建持久化类Customer
- 持久化类符合JavaBean的规范,包含一些属性,以及与之对应的getXXX()和setXXX()方法。
- 持久化类有一个id属性,用来惟一标识Customer类的每个对象。在面向对象术语中,这个id属性被称为对象标识符(OID,Object Identifier),通常它都用整数表示
- Hibernate要求持久化类必须提供一个不带参数的默认构造方法
- packagemypack;
- importjava.io.Serializable;
- importjava.sql.Date;
- importjava.sql.Timestamp;
- publicclassCustomerimplementsSerializable{
- privateLongid;
- privateStringname;
- privateStringemail;
- privateStringpassword;
- privateintphone;
- privateStringaddress;
- privatecharsex;
- privatebooleanmarried;
- privateStringdescription;
- privatebyte[]image;
- privateDatebirthday;
- privateTimestampregisteredTime;
- publicCustomer(){}
- publicLonggetId(){
- returnid;
- }
- privatevoidsetId(Longid){
- this.id=id;
- }
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicStringgetEmail(){
- returnemail;
- }
- publicvoidsetEmail(Stringemail){
- this.email=email;
- }
- publicStringgetPassword(){
- returnpassword;
- }
- publicvoidsetPassword(Stringpassword){
- this.password=password;
- }
- publicintgetPhone(){
- returnphone;
- }
- publicvoidsetPhone(intphone){
- this.phone=phone;
- }
- publicStringgetAddress(){
- returnaddress;
- }
- publicvoidsetAddress(Stringaddress){
- this.address=address;
- }
- publicchargetSex(){
- returnsex;
- }
- publicvoidsetSex(charsex){
- this.sex=sex;
- }
- publicbooleanisMarried(){
- returnmarried;
- }
- publicvoidsetMarried(booleanmarried){
- this.married=married;
- }
- publicStringgetDescription(){
- returndescription;
- }
- publicvoidsetDescription(Stringdescription){
- this.description=description;
- }
- publicbyte[]getImage(){
- returnthis.image;
- }
- publicvoidsetImage(byte[]image){
- this.image=image;
- }
- publicDategetBirthday(){
- returnthis.birthday;
- }
- publicvoidsetBirthday(Datebirthday){
- this.birthday=birthday;
- }
- publicTimestampgetRegisteredTime(){
- returnthis.registeredTime;
- }
- publicvoidsetRegisteredTime(TimestampregisteredTime){
- this.registeredTime=registeredTime;
- }
- }
注意:
- getXXX()和setXXX()方法可以采用任意的访问级别,他的命名规则必须符合特定的命名规则,“get”和“set”后面紧跟属性的名字,并且属性名的首字母为大写,如name属性的get方法为getName()。
- 如果持久化类的属性为boolean类型,那么它的get方法名可以用get做前缀也可以用is做前缀。
五、创建数据库Schema
- dropdatabaseifexistsSAMPLEDB;
- createdatabaseSAMPLEDB;
- useSAMPLEDB;
- createtableCUSTOMERS(
- IDbigintnotnullprimarykey,
- NAMEvarchar(15)notnull,
- EMAILvarchar(128)notnull,
- PASSWORDvarchar(8)notnull,
- PHONEint,
- ADDRESSvarchar(255),
- SEXchar(1),
- IS_MARRIEDbit,
- DESCRIPTIONtext,
- IMAGEblob,
- BIRTHDAYdate,
- REGISTERED_TIMEtimestamp
- );
六、创建对象-关系映射文件Customer.hbm.xml
- <?xmlversion="1.0"?>
- <!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <classname="mypack.Customer"table="CUSTOMERS">
- <idname="id"column="ID"type="long">
- <generatorclass="increment"/>
- </id>
- <propertyname="name"column="NAME"type="string"not-null="true"/>
- <propertyname="email"column="EMAIL"type="string"not-null="true"/>
- <propertyname="password"column="PASSWORD"type="string"not-null="true"/>
- <propertyname="phone"column="PHONE"type="int"/>
- <propertyname="address"column="ADDRESS"type="string"/>
- <propertyname="sex"column="SEX"type="character"/>
- <propertyname="married"column="IS_MARRIED"type="boolean"/>
- <propertyname="description"column="DESCRIPTION"type="text"/>
- <propertyname="image"column="IMAGE"type="binary"/>
- <propertyname="birthday"column="BIRTHDAY"type="date"/>
- <propertyname="registeredTime"column="REGISTERED_TIME"type="timestamp"/>
- </class>
- </hibernate-mapping>
- <id>元素映射OID
<generator>子元素用来设定标识符生成器。Hibernate提供了提供了多种内置的实现。
- <property>元素映射值类型属性
name属性:指定持久化类的属性的名字。
column属性:指定与类的属性映射的表的字段名。
type属性:指定Hibernate映射类型。Hibernate映射类型是Java类型与SQL类型的桥梁。
采用XML文件来配置对象-关系映射的优点:
- Hibernate既不会渗透到上层域模型中,也不会渗透到下层数据模型中。
- 软件开发人员可以独立设计域模型,不必强迫遵守任何规范。
- 数据库设计人员可以独立设计数据模型,不必强迫遵守任何规范。
- 对象-关系映射不依赖于任何程序代码,如果需要修改对象-关系映射,只需修改XML文件,不需要修改任何程序,提高了软件的灵活性,并且使维护更加方便。
七、创建BusinessService类
- packagemypack;
- importjavax.servlet.*;
- importorg.hibernate.*;
- importorg.hibernate.cfg.Configuration;
- importjava.io.*;
- importjava.sql.Date;
- importjava.sql.Timestamp;
- importjava.util.*;
- publicclassBusinessService{
- publicstaticSessionFactorysessionFactory;
- /**初始化Hibernate,创建SessionFactory实例*/
- static{
- try{
- //根据默认位置的Hibernate配置文件的配置信息,创建一个Configuration实例
- Configurationconfig=newConfiguration();
- //加载Customer类的对象-关系映射文件
- config.addClass(Customer.class);
- //创建SessionFactory实例*/
- sessionFactory=config.buildSessionFactory();
- }catch(RuntimeExceptione){e.printStackTrace();throwe;}
- }
- /**查询所有的Customer对象,然后调用printCustomer()方法打印Customer对象信息*/
- publicvoidfindAllCustomers(ServletContextcontext,PrintWriterout)throwsException{
- Sessionsession=sessionFactory.openSession();//创建一个会话
- Transactiontx=null;
- try{
- tx=session.beginTransaction();//开始一个事务
- Queryquery=session.createQuery("fromCustomerascorderbyc.nameasc");
- Listcustomers=query.list();
- for(Iteratorit=customers.iterator();it.hasNext();){
- printCustomer(context,out,(Customer)it.next());
- }
- tx.commit();//提交事务
- }catch(RuntimeExceptione){
- if(tx!=null){
- tx.rollback();
- }
- throwe;
- }finally{
- session.close();
- }
- }
- /**持久化一个Customer对象*/
- publicvoidsaveCustomer(Customercustomer){
- Sessionsession=sessionFactory.openSession();
- Transactiontx=null;
- try{
- tx=session.beginTransaction();
- session.save(customer);
- tx.commit();
- }catch(RuntimeExceptione){
- if(tx!=null){
- tx.rollback();
- }
- throwe;
- }finally{
- session.close();
- }
- }
- /**按照OID加载一个Customer对象,然后修改它的属性*/
- publicvoidloadAndUpdateCustomer(Longcustomer_id,Stringaddress){
- Sessionsession=sessionFactory.openSession();
- Transactiontx=null;
- try{
- tx=session.beginTransaction();
- Customerc=(Customer)session.get(Customer.class,customer_id);
- c.setAddress(address);
- tx.commit();
- }catch(RuntimeExceptione){
- if(tx!=null){
- tx.rollback();
- }
- throwe;
- }finally{
- session.close();
- }
- }
- /**删除Customer对象*/
- publicvoiddeleteCustomer(Customercustomer){
- Sessionsession=sessionFactory.openSession();
- Transactiontx=null;
- try{
- tx=session.beginTransaction();
- session.delete(customer);
- tx.commit();
- }catch(RuntimeExceptione){
- if(tx!=null){
- tx.rollback();
- }
- throwe;
- }finally{
- session.close();
- }
- }
- /**选择向控制台还是Web网页输出Customer对象的信息*/
- privatevoidprintCustomer(ServletContextcontext,PrintWriterout,Customercustomer)throwsException{
- if(context!=null)
- printCustomerInWeb(context,out,customer);
- else
- printCustomer(out,customer);
- }
- /**把Customer对象的信息输出到控制台,如DOS控制台*/
- privatevoidprintCustomer(PrintWriterout,Customercustomer)throwsException{
- byte[]buffer=customer.getImage();
- FileOutputStreamfout=newFileOutputStream("photo_copy.gif");
- fout.write(buffer);
- fout.close();
- out.println("------以下是"+customer.getName()+"的个人信息------");
- out.println("ID:"+customer.getId());
- out.println("口令:"+customer.getPassword());
- out.println("E-Mail:"+customer.getEmail());
- out.println("电话:"+customer.getPhone());
- out.println("地址:"+customer.getAddress());
- Stringsex=customer.getSex()=='M'?"男":"女";
- out.println("性别:"+sex);
- StringmarriedStatus=customer.isMarried()?"已婚":"未婚";
- out.println("婚姻状况:"+marriedStatus);
- out.println("生日:"+customer.getBirthday());
- out.println("注册时间:"+customer.getRegisteredTime());
- out.println("自我介绍:"+customer.getDescription());
- }
- /**把Customer对象的信息输出到动态网页*/
- privatevoidprintCustomerInWeb(ServletContextcontext,PrintWriterout,Customercustomer)throwsException{
- //保存照片
- byte[]buffer=customer.getImage();
- Stringpath=context.getRealPath("/");
- FileOutputStreamfout=newFileOutputStream(path+"photo_copy.gif");
- fout.write(buffer);
- fout.close();
- out.println("------以下是"+customer.getName()+"的个人信息------"+"<br>");
- out.println("ID:"+customer.getId()+"<br>");
- out.println("口令:"+customer.getPassword()+"<br>");
- out.println("E-Mail:"+customer.getEmail()+"<br>");
- out.println("电话:"+customer.getPhone()+"<br>");
- out.println("地址:"+customer.getAddress()+"<br>");
- Stringsex=customer.getSex()=='M'?"男":"女";
- out.println("性别:"+sex+"<br>");
- StringmarriedStatus=customer.isMarried()?"已婚":"未婚";
- out.println("婚姻状况:"+marriedStatus+"<br>");
- out.println("生日:"+customer.getBirthday()+"<br>");
- out.println("注册时间:"+customer.getRegisteredTime()+"<br>");
- out.println("自我介绍:"+customer.getDescription()+"<br>");
- out.println("<imgsrc='photo_copy.gif'border=0><p>");
- }
- publicvoidtest(ServletContextcontext,PrintWriterout)throwsException{
- Customercustomer=newCustomer();
- customer.setName("Tom");
- customer.setEmail("[email protected]");
- customer.setPassword("1234");
- customer.setPhone(55556666);
- customer.setAddress("Shanghai");
- customer.setSex('M');
- customer.setDescription("Iamveryhonest.");
- //设置Customer对象的image属性,它是字节数组,存放photo.gif文件中的二进制数据
- //photo.gif文件和BusinessService.class文件位于同一个目录下
- InputStreamin=this.getClass().getResourceAsStream("photo.gif");
- byte[]buffer=newbyte[in.available()];
- in.read(buffer);
- customer.setImage(buffer);
- //设置Customer对象的birthday属性,它是java.sql.Date类型
- customer.setBirthday(Date.valueOf("1980-05-06"));
- saveCustomer(customer);
- findAllCustomers(context,out);
- loadAndUpdateCustomer(customer.getId(),"Beijing");
- findAllCustomers(context,out);
- deleteCustomer(customer);
- }
- publicstaticvoidmain(Stringargs[])throwsException{
- newBusinessService().test(null,newPrintWriter(System.out,true));
- sessionFactory.close();
- }
- }
- saveCustomer()方法
该方法调用Session的save()方法,把Customer对象持久化到数据库中。
- tx=session.beginTransaction();
- session.save(customer);
- tx.commit();
当运行session.save()方法时,Hibernate执行以下SQL语句:
- insertintoCUSTOMERS(ID,NAME,EMAIL,PASSWORD,PHONE,ADDRESS,SEX,
- IS_MARRIED,DESCRIPTION,IMAGE,BIRTHDAY,REGISTERED_TIME)
- values(1,'Tom','[email protected]','1234',55556666,'Shanghai','M',0,'Iamveryhonest.',☺,'1980-05-06',null)
在test()方法中并没有设置Customer对象的id属性,Hibernate会根据映射文件的配置,采用increment标识符生成器自动以递增的方式为OID赋值。在Customer.hbm.xml文件中相关的映射代码如下:
- <idname="id"column="ID"type="long">
- <generatorclass="increment"/>
- </id>
- findAllCustomers()方法
该方法通过Query接口查询所有的Customer对象。
- tx=session.beginTransaction();//开始一个事务
- Queryquery=session.createQuery("fromCustomerascorderbyc.nameasc");
- Listcustomers=query.list();
- for(Iteratorit=customers.iterator();it.hasNext();){
- printCustomer(context,out,(Customer)it.next());
- }
- tx.commit();//提交事务
Session的createQuery()方法的参数“from Customer as c order by c.name asc”使用的是Hibernate查询语言。运行Query.list()方法时, Hibernate执行以下SQL语句:
- select*fromCUSTOMERSorderbyNAMEasc;
- loadAndUpdateCustomer ()方法
该方法调用Session的get()方法,加载Customer对象,然后再修改Customer对象的属性。
- tx=session.beginTransaction();
- Customerc=(Customer)session.get(Customer.class,customer_id);
- c.setAddress(address);//修改内存中Customer对象的address属性
- tx.commit();
以上代码先调用Session的get()方法,它按照参数指定的OID从数据库中检索出匹配的Customer对象,Hibernate会执行以下SQL语句:
- select*fromCUSTOMERSwhereID=1;
loadAndUpdateCustomer()方法接着修改Customer对象的address属性。那么,Hibernate会不会同步更新数据库中相应的CUSTOMERS表的记录呢?答案是肯定的。Hibernate采用脏检查机制,按照内存中的Customer对象的状态的变化,来同步更新数据库中相关的数据,Hibernate会执行以下SQL语句:
- updateCUSTOMERSsetNAME="Tom",EMAIL="[email protected]"…ADDRESS="Beijing"…
- whereID=1;
尽管只有Customer对象的address属性发生了变化,但是Hibernate执行的update语句中会包含所有的字段。
- deleteCustomer()方法
该方法调用Session的delete()方法,删除特定的Customer对象:
- tx=session.beginTransaction();
- session.delete(customer);
- tx.commit();
运行session.delete()方法时,Hibernate根据Customer对象的OID,执行以下SQL delete语句:
- deletefromCUSTOMERSwhereID=1;
八、效果图
一、在Java应用中使用Hibernate的步骤
- 创建Hibernate的配置文件
- 创建持久化类
- 创建对象-关系映射文件
- 通过Hibernate API编写访问数据库的代码
二、Helloapp应用的结构
三、Hibernate的配置文件(hibernate.properties)
- hibernate.dialect=org.hibernate.dialect.MySQLDialect
- hibernate.connection.driver_class=com.mysql.jdbc.Driver
- hibernate.connection.url=jdbc:mysql://localhost:3306/SAMPLEDB
- hibernate.connection.username=root
- hibernate.connection.password=1234
- hibernate.show_sql=true
四、创建持久化类Customer
- 持久化类符合JavaBean的规范,包含一些属性,以及与之对应的getXXX()和setXXX()方法。
- 持久化类有一个id属性,用来惟一标识Customer类的每个对象。在面向对象术语中,这个id属性被称为对象标识符(OID,Object Identifier),通常它都用整数表示
- Hibernate要求持久化类必须提供一个不带参数的默认构造方法
- packagemypack;
- importjava.io.Serializable;
- importjava.sql.Date;
- importjava.sql.Timestamp;
- publicclassCustomerimplementsSerializable{
- privateLongid;
- privateStringname;
- privateStringemail;
- privateStringpassword;
- privateintphone;
- privateStringaddress;
- privatecharsex;
- privatebooleanmarried;
- privateStringdescription;
- privatebyte[]image;
- privateDatebirthday;
- privateTimestampregisteredTime;
- publicCustomer(){}
- publicLonggetId(){
- returnid;
- }
- privatevoidsetId(Longid){
- this.id=id;
- }
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicStringgetEmail(){
- returnemail;
- }
- publicvoidsetEmail(Stringemail){
- this.email=email;
- }
- publicStringgetPassword(){
- returnpassword;
- }
- publicvoidsetPassword(Stringpassword){
- this.password=password;
- }
- publicintgetPhone(){
- returnphone;
- }
- publicvoidsetPhone(intphone){
- this.phone=phone;
- }
- publicStringgetAddress(){
- returnaddress;
- }
- publicvoidsetAddress(Stringaddress){
- this.address=address;
- }
- publicchargetSex(){
- returnsex;
- }
- publicvoidsetSex(charsex){
- this.sex=sex;
- }
- publicbooleanisMarried(){
- returnmarried;
- }
- publicvoidsetMarried(booleanmarried){
- this.married=married;
- }
- publicStringgetDescription(){
- returndescription;
- }
- publicvoidsetDescription(Stringdescription){
- this.description=description;
- }
- publicbyte[]getImage(){
- returnthis.image;
- }
- publicvoidsetImage(byte[]image){
- this.image=image;
- }
- publicDategetBirthday(){
- returnthis.birthday;
- }
- publicvoidsetBirthday(Datebirthday){
- this.birthday=birthday;
- }
- publicTimestampgetRegisteredTime(){
- returnthis.registeredTime;
- }
- publicvoidsetRegisteredTime(TimestampregisteredTime){
- this.registeredTime=registeredTime;
- }
- }
注意:
- getXXX()和setXXX()方法可以采用任意的访问级别,他的命名规则必须符合特定的命名规则,“get”和“set”后面紧跟属性的名字,并且属性名的首字母为大写,如name属性的get方法为getName()。
- 如果持久化类的属性为boolean类型,那么它的get方法名可以用get做前缀也可以用is做前缀。
五、创建数据库Schema
- dropdatabaseifexistsSAMPLEDB;
- createdatabaseSAMPLEDB;
- useSAMPLEDB;
- createtableCUSTOMERS(
- IDbigintnotnullprimarykey,
- NAMEvarchar(15)notnull,
- EMAILvarchar(128)notnull,
- PASSWORDvarchar(8)notnull,
- PHONEint,
- ADDRESSvarchar(255),
- SEXchar(1),
- IS_MARRIEDbit,
- DESCRIPTIONtext,
- IMAGEblob,
- BIRTHDAYdate,
- REGISTERED_TIMEtimestamp
- );
六、创建对象-关系映射文件Customer.hbm.xml
- <?xmlversion="1.0"?>
- <!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <classname="mypack.Customer"table="CUSTOMERS">
- <idname="id"column="ID"type="long">
- <generatorclass="increment"/>
- </id>
- <propertyname="name"column="NAME"type="string"not-null="true"/>
- <propertyname="email"column="EMAIL"type="string"not-null="true"/>
- <propertyname="password"column="PASSWORD"type="string"not-null="true"/>
- <propertyname="phone"column="PHONE"type="int"/>
- <propertyname="address"column="ADDRESS"type="string"/>
- <propertyname="sex"column="SEX"type="character"/>
- <propertyname="married"column="IS_MARRIED"type="boolean"/>
- <propertyname="description"column="DESCRIPTION"type="text"/>
- <propertyname="image"column="IMAGE"type="binary"/>
- <propertyname="birthday"column="BIRTHDAY"type="date"/>
- <propertyname="registeredTime"column="REGISTERED_TIME"type="timestamp"/>
- </class>
- </hibernate-mapping>
- <id>元素映射OID
<generator>子元素用来设定标识符生成器。Hibernate提供了提供了多种内置的实现。
- <property>元素映射值类型属性
name属性:指定持久化类的属性的名字。
column属性:指定与类的属性映射的表的字段名。
type属性:指定Hibernate映射类型。Hibernate映射类型是Java类型与SQL类型的桥梁。
采用XML文件来配置对象-关系映射的优点:
- Hibernate既不会渗透到上层域模型中,也不会渗透到下层数据模型中。
- 软件开发人员可以独立设计域模型,不必强迫遵守任何规范。
- 数据库设计人员可以独立设计数据模型,不必强迫遵守任何规范。
- 对象-关系映射不依赖于任何程序代码,如果需要修改对象-关系映射,只需修改XML文件,不需要修改任何程序,提高了软件的灵活性,并且使维护更加方便。
七、创建BusinessService类
- packagemypack;
- importjavax.servlet.*;
- importorg.hibernate.*;
- importorg.hibernate.cfg.Configuration;
- importjava.io.*;
- importjava.sql.Date;
- importjava.sql.Timestamp;
- importjava.util.*;
- publicclassBusinessService{
- publicstaticSessionFactorysessionFactory;
- /**初始化Hibernate,创建SessionFactory实例*/
- static{
- try{
- //根据默认位置的Hibernate配置文件的配置信息,创建一个Configuration实例
- Configurationconfig=newConfiguration();
- //加载Customer类的对象-关系映射文件
- config.addClass(Customer.class);
- //创建SessionFactory实例*/
- sessionFactory=config.buildSessionFactory();
- }catch(RuntimeExceptione){e.printStackTrace();throwe;}
- }
- /**查询所有的Customer对象,然后调用printCustomer()方法打印Customer对象信息*/
- publicvoidfindAllCustomers(ServletContextcontext,PrintWriterout)throwsException{
- Sessionsession=sessionFactory.openSession();//创建一个会话
- Transactiontx=null;
- try{
- tx=session.beginTransaction();//开始一个事务
- Queryquery=session.createQuery("fromCustomerascorderbyc.nameasc");
- Listcustomers=query.list();
- for(Iteratorit=customers.iterator();it.hasNext();){
- printCustomer(context,out,(Customer)it.next());
- }
- tx.commit();//提交事务
- }catch(RuntimeExceptione){
- if(tx!=null){
- tx.rollback();
- }
- throwe;
- }finally{
- session.close();
- }
- }
- /**持久化一个Customer对象*/
- publicvoidsaveCustomer(Customercustomer){
- Sessionsession=sessionFactory.openSession();
- Transactiontx=null;
- try{
- tx=session.beginTransaction();
- session.save(customer);
- tx.commit();
- }catch(RuntimeExceptione){
- if(tx!=null){
- tx.rollback();
- }
- throwe;
- }finally{
- session.close();
- }
- }
- /**按照OID加载一个Customer对象,然后修改它的属性*/
- publicvoidloadAndUpdateCustomer(Longcustomer_id,Stringaddress){
- Sessionsession=sessionFactory.openSession();
- Transactiontx=null;
- try{
- tx=session.beginTransaction();
- Customerc=(Customer)session.get(Customer.class,customer_id);
- c.setAddress(address);
- tx.commit();
- }catch(RuntimeExceptione){
- if(tx!=null){
- tx.rollback();
- }
- throwe;
- }finally{
- session.close();
- }
- }
- /**删除Customer对象*/
- publicvoiddeleteCustomer(Customercustomer){
- Sessionsession=sessionFactory.openSession();
- Transactiontx=null;
- try{
- tx=session.beginTransaction();
- session.delete(customer);
- tx.commit();
- }catch(RuntimeExceptione){
- if(tx!=null){
- tx.rollback();
- }
- throwe;
- }finally{
- session.close();
- }
- }
- /**选择向控制台还是Web网页输出Customer对象的信息*/
- privatevoidprintCustomer(ServletContextcontext,PrintWriterout,Customercustomer)throwsException{
- if(context!=null)
- printCustomerInWeb(context,out,customer);
- else
- printCustomer(out,customer);
- }
- /**把Customer对象的信息输出到控制台,如DOS控制台*/
- privatevoidprintCustomer(PrintWriterout,Customercustomer)throwsException{
- byte[]buffer=customer.getImage();
- FileOutputStreamfout=newFileOutputStream("photo_copy.gif");
- fout.write(buffer);
- fout.close();
- out.println("------以下是"+customer.getName()+"的个人信息------");
- out.println("ID:"+customer.getId());
- out.println("口令:"+customer.getPassword());
- out.println("E-Mail:"+customer.getEmail());
- out.println("电话:"+customer.getPhone());
- out.println("地址:"+customer.getAddress());
- Stringsex=customer.getSex()=='M'?"男":"女";
- out.println("性别:"+sex);
- StringmarriedStatus=customer.isMarried()?"已婚":"未婚";
- out.println("婚姻状况:"+marriedStatus);
- out.println("生日:"+customer.getBirthday());
- out.println("注册时间:"+customer.getRegisteredTime());
- out.println("自我介绍:"+customer.getDescription());
- }
- /**把Customer对象的信息输出到动态网页*/
- privatevoidprintCustomerInWeb(ServletContextcontext,PrintWriterout,Customercustomer)throwsException{
- //保存照片
- byte[]buffer=customer.getImage();
- Stringpath=context.getRealPath("/");
- FileOutputStreamfout=newFileOutputStream(path+"photo_copy.gif");
- fout.write(buffer);
- fout.close();
- out.println("------以下是"+customer.getName()+"的个人信息------"+"<br>");
- out.println("ID:"+customer.getId()+"<br>");
- out.println("口令:"+customer.getPassword()+"<br>");
- out.println("E-Mail:"+customer.getEmail()+"<br>");
- out.println("电话:"+customer.getPhone()+"<br>");
- out.println("地址:"+customer.getAddress()+"<br>");
- Stringsex=customer.getSex()=='M'?"男":"女";
- out.println("性别:"+sex+"<br>");
- StringmarriedStatus=customer.isMarried()?"已婚":"未婚";
- out.println("婚姻状况:"+marriedStatus+"<br>");
- out.println("生日:"+customer.getBirthday()+"<br>");
- out.println("注册时间:"+customer.getRegisteredTime()+"<br>");
- out.println("自我介绍:"+customer.getDescription()+"<br>");
- out.println("<imgsrc='photo_copy.gif'border=0><p>");
- }
- publicvoidtest(ServletContextcontext,PrintWriterout)throwsException{
- Customercustomer=newCustomer();
- customer.setName("Tom");
- customer.setEmail("[email protected]");
- customer.setPassword("1234");
- customer.setPhone(55556666);
- customer.setAddress("Shanghai");
- customer.setSex('M');
- customer.setDescription("Iamveryhonest.");
- //设置Customer对象的image属性,它是字节数组,存放photo.gif文件中的二进制数据
- //photo.gif文件和BusinessService.class文件位于同一个目录下
- InputStreamin=this.getClass().getResourceAsStream("photo.gif");
- byte[]buffer=newbyte[in.available()];
- in.read(buffer);
- customer.setImage(buffer);
- //设置Customer对象的birthday属性,它是java.sql.Date类型
- customer.setBirthday(Date.valueOf("1980-05-06"));
- saveCustomer(customer);
- findAllCustomers(context,out);
- loadAndUpdateCustomer(customer.getId(),"Beijing");
- findAllCustomers(context,out);
- deleteCustomer(customer);
- }
- publicstaticvoidmain(Stringargs[])throwsException{
- newBusinessService().test(null,newPrintWriter(System.out,true));
- sessionFactory.close();
- }
- }
- saveCustomer()方法
该方法调用Session的save()方法,把Customer对象持久化到数据库中。
- tx=session.beginTransaction();
- session.save(customer);
- tx.commit();
当运行session.save()方法时,Hibernate执行以下SQL语句:
- insertintoCUSTOMERS(ID,NAME,EMAIL,PASSWORD,PHONE,ADDRESS,SEX,
- IS_MARRIED,DESCRIPTION,IMAGE,BIRTHDAY,REGISTERED_TIME)
- values(1,'Tom','[email protected]','1234',55556666,'Shanghai','M',0,'Iamveryhonest.',☺,'1980-05-06',null)
在test()方法中并没有设置Customer对象的id属性,Hibernate会根据映射文件的配置,采用increment标识符生成器自动以递增的方式为OID赋值。在Customer.hbm.xml文件中相关的映射代码如下:
- <idname="id"column="ID"type="long">
- <generatorclass="increment"/>
- </id>
- findAllCustomers()方法
该方法通过Query接口查询所有的Customer对象。
- tx=session.beginTransaction();//开始一个事务
- Queryquery=session.createQuery("fromCustomerascorderbyc.nameasc");
- Listcustomers=query.list();
- for(Iteratorit=customers.iterator();it.hasNext();){
- printCustomer(context,out,(Customer)it.next());
- }
- tx.commit();//提交事务
Session的createQuery()方法的参数“from Customer as c order by c.name asc”使用的是Hibernate查询语言。运行Query.list()方法时, Hibernate执行以下SQL语句:
- select*fromCUSTOMERSorderbyNAMEasc;
- loadAndUpdateCustomer ()方法
该方法调用Session的get()方法,加载Customer对象,然后再修改Customer对象的属性。
- tx=session.beginTransaction();
- Customerc=(Customer)session.get(Customer.class,customer_id);
- c.setAddress(address);//修改内存中Customer对象的address属性
- tx.commit();
以上代码先调用Session的get()方法,它按照参数指定的OID从数据库中检索出匹配的Customer对象,Hibernate会执行以下SQL语句:
- select*fromCUSTOMERSwhereID=1;
loadAndUpdateCustomer()方法接着修改Customer对象的address属性。那么,Hibernate会不会同步更新数据库中相应的CUSTOMERS表的记录呢?答案是肯定的。Hibernate采用脏检查机制,按照内存中的Customer对象的状态的变化,来同步更新数据库中相关的数据,Hibernate会执行以下SQL语句:
- updateCUSTOMERSsetNAME="Tom",EMAIL="[email protected]"…ADDRESS="Beijing"…
- whereID=1;
尽管只有Customer对象的address属性发生了变化,但是Hibernate执行的update语句中会包含所有的字段。
- deleteCustomer()方法
该方法调用Session的delete()方法,删除特定的Customer对象:
- tx=session.beginTransaction();
- session.delete(customer);
- tx.commit();
运行session.delete()方法时,Hibernate根据Customer对象的OID,执行以下SQL delete语句:
- deletefromCUSTOMERSwhereID=1;
八、效果图