第一个Hibernate应用

1.创建配置文件

hibernate.cfg.xml:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration
 PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory >
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/sampledb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">1234</property>
    <property name="show_sql">true</property>

    <mapping resource="com.mypack/Customer.hbm.xml" />
  </session-factory>
</hibernate-configuration>

2.创建持久化类

Customer.java:

package com.mypack;

import java.util.Date;

public class Customer  implements java.io.Serializable {
     private long id;
     private String name;
     private Date registeredTime;
     private int age;
     private char sex;
     private boolean married;
     private String description;

    public Customer() {
    }

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Customer(String name, Date registeredTime, int age, char sex, boolean married, String description) {
       this.name = name;
       this.registeredTime = registeredTime;
       this.age = age;
       this.sex = sex;
       this.married = married;
       this.description = description;
    }
   
    public long getId() {
        return this.id;
    }
    
    private void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public Date getRegisteredTime() {
        return this.registeredTime;
    }
    
    public void setRegisteredTime(Date registeredTime) {
        this.registeredTime = registeredTime;
    }
    
    public int getAge() {
        return this.age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    public char getSex() {
        return this.sex;
    }
    
    public void setSex(char sex) {
        this.sex = sex;
    }
    
    public boolean isMarried() {
        return this.married;
    }
    
    public void setMarried(boolean married) {
        this.married = married;
    }
    public String getDescription() {
        return this.description;
    }
    
    public void setDescription(String description) {
        this.description = description;
    }

       public String toString() {
	  
           StringBuffer buffer = new StringBuffer();

      buffer.append(getClass().getName()).append("@").append(Integer.toHexString(hashCode())).append(" [");
      buffer.append("name").append("='").append(getName()).append("' ");			
      buffer.append("registeredTime").append("='").append(getRegisteredTime()).append("' ");			
      buffer.append("age").append("='").append(getAge()).append("' ");			
      buffer.append("married").append("='").append(isMarried()).append("' ");			
      buffer.append("description").append("='").append(getDescription()).append("' ");			
      buffer.append("]");
      
      return buffer.toString();
     }

}
 

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

3.创建数据库Schema

drop table if exists CUSTOMERS;

create table CUSTOMERS (
ID bigint not null auto_increment, 
NAME varchar(15) not null unique, 
REGISTERED_TIME timestamp, 
AGE integer not null check (AGE>10), 
SEX char(1), 
IS_MARRIED bit, 
DESCRIPTION text, 
primary key (ID));

create index IDX_REGISTERED_TIME on CUSTOMERS (REGISTERED_TIME);
 
 

4.创建对象-关系映射文件

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="com.mypack.Customer" table="CUSTOMERS" >
    
    <id name="id" type="long" column="ID" >
      <meta attribute="scope-set">private</meta>
      <generator class="native"/>
    </id>

    <property name="name" type="string" >
      <meta attribute="use-in-tostring">true</meta>
      <column name="NAME" length="15" not-null="true" unique="true" />
    </property>
    
    <property name="registeredTime" type="timestamp" >
      <meta attribute="use-in-tostring">true</meta>
      <column name="REGISTERED_TIME" index="IDX_REGISTERED_TIME" sql-type="timestamp" />
    </property>
    
     
    <property name="age" type="int">
      <meta attribute="use-in-tostring">true</meta>
      <column name="AGE" check="AGE>10" not-null="true"/>
    </property>
    
    <property name="sex" type="char" column="SEX"/>
    
    <property name="married" type="boolean" column="IS_MARRIED">
      <meta attribute="use-in-tostring">true</meta>
    </property>

    <property name="description" type="string">
       <meta attribute="use-in-tostring">true</meta>
       <column name="DESCRIPTION" sql-type="text"/>
    </property>
	
  </class>
 
</hibernate-mapping>



注:在<class>元素中,<id>子元素必须存在且只能存在一次,必须先定义<id>子元素,再定义<property>子元素。

<id>子元素设定持久化类的OID和表的主键的映射,<property>子元素设定类的属性和表的字段的映射。

5.通过Hibernate API操作数据库

package com.mypack;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import java.io.*;
import java.sql.Time;
import java.util.*;

public class BusinessService{
  public static SessionFactory sessionFactory;
  static{
     try{
      Configuration config = new Configuration().configure();
      config.addClass(Customer.class);
      StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(config.getProperties());
      sessionFactory = config.buildSessionFactory(builder.build());
    }catch(RuntimeException e){e.printStackTrace();throw e;}
  }

  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 Customer loadCustomer(Long id){
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      Customer customer=(Customer)session.get(Customer.class,id);
      tx.commit();
      return customer;
    }catch (RuntimeException e) {
      if (tx != null) {
        tx.rollback();
      }
      throw e;
    } finally {
      session.close();
    }
  }

  public void printCustomer(Customer customer){
    System.out.println(customer);
  }

  public void test(){
    Customer customer=new Customer();
    customer.setName("Tom");
    customer.setAge(new Integer(21));
    customer.setSex(new Character('M'));
    customer.setMarried(new Boolean(false));
    customer.setDescription("I am very honest.");
    saveCustomer(customer);
    customer=loadCustomer(customer.getId());
    printCustomer(customer);
  }

  public static void main(String args[]){
    new BusinessService().test();
    sessionFactory.close();
  }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值