Hibernate实战——使用传统的映射文件

一 配置文件

<?xml version="1.0" encoding="GBK"?>
<!-- 指定Hibernate配置文件的DTD信息 -->
<!DOCTYPE hibernate-configuration PUBLIC
     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- hibernate-configuration是配置文件的根元素 -->
<hibernate-configuration>
     <session-factory>
           <!-- 指定连接数据库所用的驱动 -->
           <property  name="connection.driver_class">com.mysql.jdbc.Driver</property>
           <!-- 指定连接数据库的url,其中hibernate是本应用连接的数据库名 -->
           <property  name="connection.url">jdbc:mysql://localhost/hibernate</property>
           <!-- 指定连接数据库的用户名 -->
           <property name="connection.username">root</property>
           <!-- 指定连接数据库的密码 -->
           <property name="connection.password">32147</property>
           <!-- 指定连接池里最大连接数 -->
           <property  name="hibernate.c3p0.max_size">20</property>
           <!-- 指定连接池里最小连接数 -->
           <property name="hibernate.c3p0.min_size">1</property>
           <!-- 指定连接池里连接的超时时长 -->
           <property  name="hibernate.c3p0.timeout">5000</property>
           <!-- 指定连接池里最大缓存多少个Statement对象 -->
           <property  name="hibernate.c3p0.max_statements">100</property>
           <property  name="hibernate.c3p0.idle_test_period">3000</property>
           <property  name="hibernate.c3p0.acquire_increment">2</property>
           <property  name="hibernate.c3p0.validate">true</property>
           <!-- 指定数据库方言 -->
           <property  name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
           <!-- 根据需要自动创建数据库 -->
           <property name="hbm2ddl.auto">update</property>
           <!-- 显示Hibernate持久化操作所生成的SQL -->
           <property name="show_sql">true</property>
           <!-- 将SQL脚本进行格式化后再输出 -->
           <property name="hibernate.format_sql">true</property>
           <!-- 罗列所有持久化类的映射文件 -->
           <mapping  resource="org/crazyit/app/domain/Person.hbm.xml"/>
     </session-factory>
</hibernate-configuration>

二 PO

1 Person

package org.crazyit.app.domain;

public class Person
{
     // 使用Name组件作为复合主键
     private Name name;
     // 普通属性
     private String email;
     // 组件属性,代表此人拥有的宠物
     private Cat pet;
     // 无参数的构造器
     public Person()
     {
     }
     // 初始化全部成员变量的构造器
     public Person(Name name , String email , Cat pet)
     {
           this.name = name;
           this.email = email;
           this.pet = pet;
     }
     // name的setter和getter方法
     public void setName(Name name)
     {
           this.name = name;
     }
     public Name getName()
     {
           return this.name;
     }
     // email的setter和getter方法
     public void setEmail(String email)
     {
           this.email = email;
     }
     public String getEmail()
     {
           return this.email;
     }
     // pet的setter和getter方法
     public void setPet(Cat pet)
     {
           this.pet = pet;
     }
     public Cat getPet()
     {
           return this.pet;
     }
}

2 Cat

package org.crazyit.app.domain;

public class Cat
{
     private String name;
     private String color;
     private Person owner;
     // 无参数的构造器
     public Cat()
     {
     }
     // 初始化全部成员变量的构造器
     public Cat(String name , String color)
     {
           this.name = name;
           this.color = color;
     }
     // name的setter和getter方法
     public void setName(String name)
     {
           this.name = name;
     }
     public String getName()
     {
           return this.name;
     }
     // color的setter和getter方法
     public void setColor(String color)
     {
           this.color = color;
     }
     public String getColor()
     {
           return this.color;
     }
     // owner的setter和getter方法
     public void setOwner(Person owner)
     {
           this.owner = owner;
     }
     public Person getOwner()
     {
           return this.owner;
     }
}

3 Name

package org.crazyit.app.domain;

public class Name
     implements java.io.Serializable
{
     private String first;
     private String last;
     // 无参数的构造器
     public Name()
     {
     }
     // 初始化全部成员变量的构造器
     public Name(String first , String last)
     {
           this.first = first;
           this.last = last;
     }
     // first的setter和getter方法
     public void setFirst(String first)
     {
           this.first = first;
     }
     public String getFirst()
     {
           return this.first;
     }
     // last的setter和getter方法
     public void setLast(String last)
     {
           this.last = last;
     }
     public String getLast()
     {
           return this.last;
     }
     // 重写equals()方法,根据first、last进行判断
     public boolean equals(Object obj)
     {
           if (this == obj)
           {
                return true;
           }
           if (obj != null && obj.getClass() == Name.class)
           {
                Name target = (Name)obj;
                return target.getFirst().equals(first)
                     && target.getLast().equals(last);
           }
           return false;
     }
     // 重写hashCode()方法,根据first、last计算hashCode值
     public int hashCode()
     {
           return first.hashCode() + last.hashCode() * 31;
     }
}

4 Person.hbm.xml

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE hibernate-mapping PUBLIC
     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- hibernate-mapping是映射文件的根元素 -->
<hibernate-mapping package="org.crazyit.app.domain">
     <class name="Person" table="person_inf">
           <!-- 映射组件类型的标识属性 -->
           <composite-id name="name" class="Name">
                <!-- 映射复合主键里的各个属性 -->
                <key-property name="first" type="string"/>
                <key-property name="last" type="string"/>
           </composite-id>
           <!-- 映射普通属性 -->
           <property name="email" type="string"/>
           <!-- 映射组件属性cat,组件属性的类型为Cat -->
           <component name="pet" class="Cat" >
                <!-- 指定owner属性代表容器实体 -->
                <parent name="owner"/>
                <!-- 映射组件属性的first属性 -->
                <property name="name" column="cat_name"/>
                <!-- 映射组件属性的last属性 -->
                <property name="color" column="cat_color"/>
           </component>
     </class>
</hibernate-mapping>

三 测试

1 工具类

package lee;

import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.*;
import org.hibernate.boot.registry.*;

public class HibernateUtil
{
    public static final SessionFactory sessionFactory;

    static
    {
        try
        {
            // 使用默认的hibernate.cfg.xml配置文件创建Configuration实例
            Configuration cfg = new Configuration()
                .configure();
            // 以Configuration实例来创建SessionFactory实例
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
            sessionFactory = cfg.buildSessionFactory(serviceRegistry);
        }
        catch (Throwable ex)
        {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    // ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
    public static final ThreadLocal<Session> session
        = new ThreadLocal<Session>();

    public static Session currentSession()
        throws HibernateException
    {
        Session s = session.get();
        // 如果该线程还没有Session,则创建一个新的Session
        if (s == null)
        {
            s = sessionFactory.openSession();
            // 将获得的Session变量存储在ThreadLocal变量session里
            session.set(s);
        }
        return s;
    }

    public static void closeSession()
        throws HibernateException
    {
        Session s = session.get();
        if (s != null)
            s.close();
        session.set(null);
    }
}

2 测试类

package lee;

import org.hibernate.Transaction;
import org.hibernate.Session;

import java.util.*;

import org.crazyit.app.domain.*;


public class PersonManager
{
    public static void main(String[] args)
    {
        PersonManager mgr = new PersonManager();
        mgr.createAndStorePerson();
        HibernateUtil.sessionFactory.close();
    }
    private void createAndStorePerson()
    {
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        // 创建Person对象
        Person person = new Person();
        person.setName(new Name("crazyit.org", "疯狂Java联盟"));
        person.setEmail("test@crazyit.org");
        person.setPet(new Cat("Garfield", "黄色"));
        session.save(person);
        tx.commit();
        HibernateUtil.closeSession();
    }
}

四 测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值