Hibernate应用(一):第一个Hibernate应用程序

听说Hibernate已经很久了,但是直到最近才开始和它近距离的接触。很早之前在湘计就看到过一份培训的PPT,里面说到Hibernate应用于持久层,并且Hibernate和持久化似乎形影相随,总是成双成对的出现。那么Hibernate到底是做什么用的,它有什么优点呢?关于Hibernate的一些概念诸如ORM、持久化就不赘述了,我们直接开始构建我们的一个Hibernate应用(通常我们的应用都是Web应用,这里我还是建一个Web工程,但是运行的时候我用Java Application的方式运行,这样比较容易理解,因为在Web应用中Hibernate都会和Spring等框架一起使用)

构建一个Hibernate应用我们需要准备什么东西呢?首先当然是去官网上下一个Hibernate的发布包咯,我下的是3.0。接下来我们按照如下步骤来进行

1.准备一个配置文件hibernate.cfg.xml,它里面定义了一些基本的属性,如数据库连接的相关参数、映射文件的地址等等,这个文件是必须的,Hibernate会首先解析并加载这个xml文件并存放在缓存中,我的hibernate.cfg.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >

<hibernate-configuration>

    <session-factory>

       <property name="connection.url">

           jdbc:mysql://localhost:3306/test

       </property>

       <property name="connection.driver_class">

           com.mysql.jdbc.Driver

       </property>

       <property name="connection.username">root</property>

       <property name="connection.password">111111</property>

       <property name="dialect">

           org.hibernate.dialect.MySQLDialect

       </property>

       <property name="show_sql">true</property>

       <mapping resource="cn/edu/hust/cm/mypack/Customer.hbm.xml" />

    </session-factory>

</hibernate-configuration>

2.我用的是Mysql数据库,不同的DBMS有些地方会不同。假设我现在数据库中有一张表存放顾客基本信息,我创建了一个Customer表,Schema如下所示:

CREATE TABLE `customer` (

  `id` bigint(11) NOT NULL DEFAULT '0',

  `name` varchar(40) NOT NULL DEFAULT '',

  `email` varchar(128) CHARACTER SET latin1 NOT NULL DEFAULT '',

  `password` varchar(8) NOT NULL DEFAULT '',

  `phone` int(11) DEFAULT '0',

  `address` varchar(255) DEFAULT NULL,

  `sex` char(1) CHARACTER SET latin1 DEFAULT NULL,

  `is_married` bit(1) DEFAULT NULL,

  `description` text,

  `image` blob,

  `birthday` date DEFAULT NULL,

  `registered_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP

)

3.创建一个Customer.java文件(这就是我们所说的持久化类)

 

package cn.edu.hust.cm.mypack;

 

import java.io.Serializable;

import java.sql.Date;

import java.sql.Timestamp;

 

/**

 * @author zhukai

 *

 */

public class Customer implements Serializable {

   

    private Long id;

    private String name;

    private String email;

    private String password;

    private int phone;

    private boolean married;

    private String address;

    private char sex;

    private String description;

    //private byte[] image;

    private Date birthday;

    private Timestamp registeredTime;

   

    /**

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

     */

    public Customer() {

       // TODO Auto-generated constructor stub

    }

   

    public String getAddress() {

       return address;

    }

    public void setAddress(String address) {

       this.address = address;

    }

    public String getDescription() {

       return description;

    }

    public void setDescription(String description) {

       this.description = description;

    }

    public Date getBirthday() {

       return birthday;

    }

    public void setBirthday(Date birthday) {

       this.birthday = birthday; 

    }

    public String getEmail() {

       return email;

    }

    public void setEmail(String email) {

       this.email = email;

    }

    public Long getId() {

       return id;

    }

    public void setId(Long id) {

       this.id = id;

    }

    public boolean isMarried() {

       return married;

    }

    public void setMarried(boolean married) {

       this.married = married;

    }

    public String getName() {

       return name;

    }

 

    public void setName(String name) {

       this.name = name;

    }

    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 Timestamp getRegisteredTime() {

       return registeredTime;

    }

    public void setRegisteredTime(Timestamp registeredTime) {

       this.registeredTime = registeredTime;

    }

    public char getSex() {

       return sex;

    }

    public void setSex(char sex) {

       this.sex = sex;

    }

}

注意,这个类采用的是标准JavaBean形式,通常我们都要按照这个标准来构建我们的持久化类。

4.配置映射文件

一般映射文件采用约定俗成的命名规则:类名.hbm.xml,和这个类的class文件放在一个目录下面,我的Customer.hbm.xml文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >

<hibernate-mapping>

    <class name="cn.edu.hust.cm.mypack.Customer" table="CUSTOMER">

       <id name="id" type="long">

           <column name="ID"></column>

           <generator class="increment"></generator>

       </id>

       <property name="name" type="string">

           <column name="NAME" not-null="true"></column>

       </property>

       <property name="email" type="string">

           <column name="EMAIL" not-null="true"></column>

       </property>

       <property name="password" type="string">

           <column name="PASSWORD" not-null="true"></column>

       </property>

       <property name="phone" type="integer">

           <column name="PHONE" not-null="true"></column>

       </property>

       <property name="address" type="string">

           <column name="ADDRESS"></column>

       </property>

       <property name="sex" type="character">

           <column name="SEX"></column>

       </property>

       <property name="married" type="boolean">

           <column name="IS_MARRIED"></column>

       </property>

       <property name="description" type="string"></property>

       <property name="birthday" type="date">

           <column name="BIRTHDAY"></column>

       </property>

       <property name="registeredTime" type="timestamp">

           <column name="REGISTERED_TIME"></column>

       </property>

    </class>

</hibernate-mapping>

注意,这个文件是非常关键的,它联系了我们的持久化类以及其在数据库中对应的表,具体的关系如下图所示:

映射文件就像一个字典一样,Hibernate向数据库插入数据时通过“查询”它可以知道属性对应于数据库中哪个列,从数据库中把数据读出赋给持久化类时则通过“查询”知道列对应于持久化类的哪个属性。这个比喻不是很恰当,因为并不是持久化类的所有属性都直接和表的字段匹配。

OK,现在准备工作都已经做好了,可以编写一个程序来使用Hibernate了,我的运行主程序如下所示:

package cn.edu.hust.cm.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.Iterator;

import java.util.List;

public class BusinessService {

 

    public static SessionFactory sessionFactory;

   

     /*静态块,类加载时即执行,用来初始化Hibernate,创建SessionFatory实例*/

    static{

       try{

           Configuration configuration=new Configuration();

           sessionFactory=configuration.configure().buildSessionFactory();

       }

       catch(Exception e){

           e.printStackTrace();

       }

       finally{

          

       }

      

    }

   

    /*默认的构造方法*/

    public BusinessService() {

    }

   

    public static SessionFactory getSessionFactory() {

       return sessionFactory;

    }

    /**

     * 该方法是测试入口,对各个方法进行测试

     */

    public void test(){

       Customer customer=new Customer();

       customer.setName("朱楷");

       customer.setEmail("xiaozhu87487705@163.com");

       customer.setPassword("19840827");

       customer.setPhone(1234);

       customer.setAddress("湖北省武汉市珞瑜路1037");

       customer.setSex('M');

       customer.setMarried(false);

       customer.setDescription("芒果网员工");

       customer.setBirthday(new Date(14*365*24*3600*1000));

       customer.setRegisteredTime(new Timestamp(36*365*24*3600*10000));

      

       saveCustomer(customer);

       findAllCustomers();
       loadAndUpdateCustomer(customer.getId());
       deleteAllCustomers(customer);

    }

   

    /**

     * 把一个Customer对象保存在数据库中

     */

    public void saveCustomer(Customer customer){

       Session session=sessionFactory.openSession();

       Transaction tx = null;//局部变量必须赋予初始值

       try{

           tx=session.beginTransaction();

           //事务开始

           session.save(customer);

           tx.commit();

       }

       catch(Exception e){

           if(tx!=null) tx.rollback();

           e.printStackTrace();

       }

       finally{

           session.close();

       }

    }

   

    /**

     * 查询出数据中所有的持久化对象,并显示它们的基本信息

     */

    public void findAllCustomers(){

       Session session=sessionFactory.openSession();

       Transaction tx=null;

       try{

           tx=session.beginTransaction();

           //事务开始

           Iterator customers=session.createQuery("from Customer").list().iterator();

           while(customers.hasNext()){

              Customer cs=(Customer)customers.next();

              System.out.println("姓名:"+cs.getName());

              System.out.println("性别:"+cs.getSex());

              System.out.println("电子邮箱:"+cs.getEmail());

              System.out.println("婚否:"+cs.isMarried());

           }

           tx.commit();

       }

       catch(Exception e){

           if(tx!=null) tx.rollback();

           e.printStackTrace();

       }

       finally{

           session.close();

       }

    }

   

    /**

     * 加载指定的持久化对象并对其进行修改

     * @param id 对象标识符OID

     */

    public void loadAndUpdateCustomer(long id){

       Session session=sessionFactory.openSession();

       Transaction tx=null;

       try{

           tx=session.beginTransaction();

           //事务开始

           Customer cs=(Customer)session.load(Customer.class, id);

           cs.setAddress("广东省深圳市");

           tx.commit();

       }

       catch(Exception e){

           if(tx!=null) tx.rollback();

           e.printStackTrace();

       }

       finally{

           session.close();

       }

    }

   

    public void deleteAllCustomers(Customer c){

       Session session=sessionFactory.openSession();

       Transaction tx=null;

       try{

           tx=session.beginTransaction();
           //事务开始
           session.delete(c);
           //Query query=session.createQuery("delete from Customer");
           //query.executeUpdate();
           tx.commit();

       }

       catch(Exception e){

           if(tx!=null) tx.rollback();

           e.printStackTrace();

       }

       finally{

           session.close();

       }

    }

    /**

     * @param args

     */

    public static void main(String[] args) {

        BusinessService bs=new BusinessService();

        bs.test(); 

        sessionFactory.close();

    }

}

这样,我们的第一个Hibernate应用程序就大功告成了,至于Hibernate中的各个类以及接口如SessionSessionFactory接口是干什么用的,在以后的学习中再陆续介绍,主要是因为我还没有好好的学习这几个类,^_^

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值