在Java应用中使用Hibernate的示例分析
这篇文章给大家介绍在Java应用中使用Hibernate的示例分析,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
一、在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要求持久化类必须提供一个不带参数的默认构造方法
package mypack; import java.io.Serializable; import java.sql.Date; import java.sql.Timestamp; public class Customer implements Serializable { private Long id; private String name; private String email; private String password; private int phone; private String address; private char sex; private boolean married; private String description; private byte[] image; private Date birthday; private Timestamp registeredTime; public Customer(){} public Long getId(){ return id; } private void setId(Long id){ this.id = id; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public String getEmail(){ return email; } public void setEmail(String email){ this.email =email ; } public String getPassword(){ return password; } public void setPassword(String password){ this.password =password ; } public int getPhone(){ return phone; } public void setPhone(int phone){ this.phone =phone ; } public String getAddress(){ return address; } public void setAddress(String address){ this.address =address ; } public char getSex(){ return sex; } public void setSex(char sex){ this.sex =sex ; } public boolean isMarried(){ return married; } public void setMarried(boolean married){ this.married =married ; } public String getDescription(){ return description; } public void setDescription(String description){ this.description =description ; } public byte[] getImage() { return this.image; } public void setImage(byte[] image) { this.image = image; } public Date getBirthday() { return this.birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Timestamp getRegisteredTime() { return this.registeredTime; } public void setRegisteredTime(Timestamp registeredTime) { this.registeredTime = registeredTime; } }
注意:
getXXX()和setXXX()方法可以采用任意的访问级别,他的命名规则必须符合特定的命名规则,“get”和“set”后面紧跟属性的名字,并且属性名的首字母为大写,如name属性的get方法为getName()。
如果持久化类的属性为boolean类型,那么它的get方法名可以用get做前缀也可以用is做前缀。
五、创建数据库Schema
drop database if exists SAMPLEDB; create database SAMPLEDB; use SAMPLEDB; create table CUSTOMERS ( ID bigint not null primary key, NAME varchar(15) not null, EMAIL varchar(128) not null, PASSWORD varchar(8) not null, PHONE int , ADDRESS varchar(255), SEX char(1) , IS_MARRIED bit, DESCRIPTION text, IMAGE blob, BIRTHDAY date, REGISTERED_TIME timestamp );
六、创建对象-关系映射文件Customer.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="mypack.Customer" table="CUSTOMERS"> <id name="id" column="ID" type="long"> <generator class="increment"/> </id> <property name="name" column="NAME" type="string" not-null="true" /> <property name="email" column="EMAIL" type="string" not-null="true" /> <property name="password" column="PASSWORD" type="string" not-null="true"/> <property name="phone" column="PHONE" type="int" /> <property name="address" column="ADDRESS" type="string" /> <property name="sex" column="SEX" type="character"/> <property name="married" column="IS_MARRIED" type="boolean"/> <property name="description" column="DESCRIPTION" type="text"/> <property name="image" column="IMAGE" type="binary"/> <property name="birthday" column="BIRTHDAY" type="date"/> <property name="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类
package mypack; import javax.servlet.*; import org.hibernate.*; import org.hibernate.cfg.Configuration; import java.io.*; import java.sql.Date; import java.sql.Timestamp; import java.util.*; public class BusinessService{ public static SessionFactory sessionFactory; static{ try{ // 根据默认位置的Hibernate配置文件的配置信息,创建一个Configuration实例 Configuration config = new Configuration(); //加载Customer类的对象-关系映射文件 config.addClass(Customer.class); // 创建SessionFactory实例 */ sessionFactory = config.buildSessionFactory(); }catch(RuntimeException e){e.printStackTrace();throw e;} } public void findAllCustomers(ServletContext context,PrintWriter out) throws Exception{ Session session = sessionFactory.openSession(); //创建一个会话 Transaction tx = null; try { tx = session.beginTransaction(); //开始一个事务 Query query=session.createQuery("from Customer as c order by c.name asc"); List customers=query.list(); for (Iterator it = customers.iterator(); it.hasNext();) { printCustomer(context,out,(Customer) it.next()); } tx.commit(); //提交事务 }catch (RuntimeException e) { if (tx != null) { tx.rollback(); } throw e; } finally { session.close(); } } public void saveCustomer(Customer customer){ Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.save(customer); tx.commit(); }catch (RuntimeException e) { if (tx != null) { tx.rollback(); } throw e; } finally { session.close(); } } public void loadAndUpdateCustomer(Long customer_id,String address){ Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Customer c=(Customer)session.get(Customer.class,customer_id); c.setAddress(address); tx.commit(); }catch (RuntimeException e) { if (tx != null) { tx.rollback(); } throw e; } finally { session.close(); } } public void deleteCustomer(Customer customer){ Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); session.delete(customer); tx.commit(); }catch (RuntimeException e) { if (tx != null) { tx.rollback(); } throw e; } finally { session.close(); } } private void printCustomer(ServletContext context,PrintWriter out,Customer customer)throws Exception{ if(context!=null) printCustomerInWeb(context,out,customer); else printCustomer( out,customer); } private void printCustomer(PrintWriter out,Customer customer)throws Exception{ byte[] buffer=customer.getImage(); FileOutputStream fout=new FileOutputStream("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()); String sex=customer.getSex()=='M'? "男":"女"; out.println("性别: "+sex); String marriedStatus=customer.isMarried()? "已婚":"未婚"; out.println("婚姻状况: "+marriedStatus); out.println("生日: "+customer.getBirthday()); out.println("注册时间: "+customer.getRegisteredTime()); out.println("自我介绍: "+customer.getDescription()); } private void printCustomerInWeb(ServletContext context,PrintWriter out,Customer customer)throws Exception{ //保存照片 byte[] buffer=customer.getImage(); String path=context.getRealPath("/"); FileOutputStream fout=new FileOutputStream(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>"); String sex=customer.getSex()=='M'? "男":"女"; out.println("性别: "+sex+"<br>"); String marriedStatus=customer.isMarried()? "已婚":"未婚"; out.println("婚姻状况: "+marriedStatus+"<br>"); out.println("生日: "+customer.getBirthday()+"<br>"); out.println("注册时间: "+customer.getRegisteredTime()+"<br>"); out.println("自我介绍: "+customer.getDescription()+"<br>"); out.println("<img class="lazy" data-src='photo_copy.gif' border=0><p>"); } public void test(ServletContext context,PrintWriter out) throws Exception{ Customer customer=new Customer(); customer.setName("Tom"); customer.setEmail("tom@yahoo.com"); customer.setPassword("1234"); customer.setPhone(55556666); customer.setAddress("Shanghai"); customer.setSex('M'); customer.setDescription("I am very honest."); //设置Customer对象的image属性,它是字节数组,存放photo.gif文件中的二进制数据 //photo.gif文件和BusinessService.class文件位于同一个目录下 InputStream in=this.getClass().getResourceAsStream("photo.gif"); byte[] buffer = new byte[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); } public static void main(String args[]) throws Exception { new BusinessService().test(null,new PrintWriter(System.out,true)); sessionFactory.close(); } }
saveCustomer()方法
该方法调用Session的save()方法,把Customer对象持久化到数据库中。
tx = session.beginTransaction(); session.save(customer); tx.commit();
当运行session.save()方法时,Hibernate执行以下SQL语句:
insert into CUSTOMERS (ID, NAME, EMAIL, PASSWORD, PHONE, ADDRESS, SEX, IS_MARRIED,DESCRIPTION, IMAGE, BIRTHDAY, REGISTERED_TIME) values(1,'Tom','tom@yahoo.com','1234',55556666,'Shanghai','M',0,'I am very honest.', ☺,'1980-05-06',null)
在test()方法中并没有设置Customer对象的id属性,Hibernate会根据映射文件的配置,采用increment标识符生成器自动以递增的方式为OID赋值。在Customer.hbm.xml文件中相关的映射代码如下:
<id name="id" column="ID" type="long"> <generator class="increment"/> </id>
findAllCustomers()方法
该方法通过Query接口查询所有的Customer对象。
tx = session.beginTransaction(); //开始一个事务 Query query=session.createQuery("from Customer as c order by c.name asc"); List customers=query.list(); for (Iterator it = 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 * from CUSTOMERS order by NAME asc;
loadAndUpdateCustomer ()方法
该方法调用Session的get()方法,加载Customer对象,然后再修改Customer对象的属性。
tx = session.beginTransaction(); Customer c=(Customer)session.get(Customer.class,customer_id); c.setAddress(address); //修改内存中Customer对象的address属性 tx.commit();
以上代码先调用Session的get()方法,它按照参数指定的OID从数据库中检索出匹配的Customer对象,Hibernate会执行以下SQL语句:
select * from CUSTOMERS where ID=1;
loadAndUpdateCustomer()方法接着修改Customer对象的address属性。那么,Hibernate会不会同步更新数据库中相应的CUSTOMERS表的记录呢?答案是肯定的。Hibernate采用脏检查机制,按照内存中的Customer对象的状态的变化,来同步更新数据库中相关的数据,Hibernate会执行以下SQL语句:
update CUSTOMERS set NAME="Tom",EMAIL="Tom@yahoo.com"…ADDRESS="Beijing"… where ID=1;
尽管只有Customer对象的address属性发生了变化,但是Hibernate执行的update语句中会包含所有的字段。
deleteCustomer()方法
该方法调用Session的delete()方法,删除特定的Customer对象:
tx = session.beginTransaction(); session.delete(customer); tx.commit();
运行session.delete()方法时,Hibernate根据Customer对象的OID,执行以下SQL delete语句:
delete from CUSTOMERS where ID=1;
八、效果图
关于在Java应用中使用Hibernate的示例分析就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341