基于Hibernate3.2 Hibernate tools 的使用

由于新发布的Hibernate Tools是一个比较庞大的工具包 而且已经是作为Eclipse3.2 的插件发布的
然而以前的很有用的工具hbm2java和hbm2ddl都是非常有用的工具

所以我们应该把这些有用的工具找出来继续使用 

环境

jdk-1_5_0_07

ant 1.6.5

Hibernate 3.2 cr2

Hibernate Tools-3.2.0.beta6

mysql-5.0.22

首先下载Hibernate Tools的包

在HIbernate的主页上有连接 下载是在sourceforge.net

地址:http://prdownloads.sourceforge.net/jboss/HibernateTools-3.2.0.beta6a.zip?download

下载完了以后解压缩HibernateTools-3.2.0.beta6a\plugins\org.hibernate.eclipse_3.2.0.beta6a\lib\tools

里找到hibernate-tools.jar 放到你的工程的lib里

目录结构

.
    +src
        +  your package
            *.java
            *.hbm.xml
            ...
        hibernate.config.xml
        ...
    +lib
    ......
    +data

    build.xml
把hibernate的目录里的lib里的jar  还有hibernate3.jar copy到lib里别忘了hibernate-tools.jar

注意hibernate3.jar要用HibernateTools-3.2.0.beta6a\plugins\org.hibernate.eclipse_3.2.0.beta6a\lib\hibernate里的hibernate3.jar

还有mysql-connector-java-5.0.0-beta-bin.jar 这个连接驱动也少不了

另外还要把HibernateTools-3.2.0.beta6a\plugins\org.hibernate.eclipse_3.2.0.beta6a\lib\tools的freemarker.jar也copy到lib里

尽管HIbernate的自动产生代码的方式有很多

比如

1 写java 代码用Xdoclet来产生hbm.xml

2 写hbm.xml来产生java代码

3 写hbm.xml来产生ddl

4 从数据库来产生hbm.xml和ddl

这里先讲解hbm2java 和 hbm2ddl

1 --hbm2java

把写好的代码*.hbm.xml放在你的src的包里

比如这样的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="ergal.Customer" table="CUSTOMERS" lazy="false">
        <id name="id" type="long" column="ID">
            <generator class="increment" />
        </id>
   
        <property name="name" type="string">
            <column name="NAME" length="15" />
        </property>
        <set
            name="orders"
            cascade="save-update"
            inverse="true"
            >
       
            <key column="CUSTOMER_ID" />
            <one-to-many class="ergal.Order" />
        </set>  
    </class>
</hibernate-mapping>
还有Order.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="ergal.Order" table="ORDERS">
        <id name="id" type="long" column="ID">
            <generator class="increment" />
        </id>
   
        <property name="orderNumber" type="string">
            <column name="ORDERNUMBER" length="15" />
        </property>
       
        <many-to-one
            name="customer"
            column="CUSTOMER_ID"
            class="ergal.Customer"
            not-null="true"
            cascade="save-update"
        />
    </class>
</hibernate-mapping>
再然后写Hibernate的配置文件

hibernate.config.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>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/ahtest</property>
        <property name="connection.username">root</property>
        <property name="connection.password">********</property>
       


        <!-- JDBC connection pool (use the built-in)-->
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
    <property name="hibernate.c3p0.max_size">20</property>
   
    <property name="hibernate.c3p0.min_size">5</property>
   
    <property name="hibernate.c3p0.timeout">120</property>
   
    <property name="hibernate.c3p0.max_statements">100</property>
   
    <property name="hibernate.c3p0.idle_test_period">120</property>
   
    <property name="hibernate.c3p0.acquire_increment">2</property>


        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management-->
        <property name="current_session_context_class">thread</property>
    
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
   
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup-->
        <property name="hbm2ddl.auto">create</property>
    
        <mapping resource="ergal/Customer.hbm.xml"/>
        <mapping resource="ergal/Order.hbm.xml"/> 

    </session-factory>

</hibernate-configuration>



最后写build.xml



<?xml version="1.0" encoding="GBK"?>

<project name="hibernate-tutorial" default="compile">

    <property name="sourcedir" value="${basedir}/src"/>
    <property name="targetdir" value="${basedir}/bin"/>
    <property name="librarydir" value="${basedir}/lib"/>
    <property name="schema.dir" value="${basedir}/data"/>
   
    <path id="libraries">
        <fileset dir="${librarydir}">
            <include name="*.jar"/>
        </fileset>
    </path>
    <path id="project.class.path">
    <!-- Include our own classes, of course -->
        <pathelement location="${targetdir}" />
    <!-- Include jars in the project library directory -->
        <fileset dir="${librarydir}">
            <include name="*.jar"/>
        </fileset>
    </path>

    <target name="clean">
        <delete dir="${targetdir}"/>
        <mkdir dir="${targetdir}"/>
    </target>

    <target name="copy-resources">
        <copy todir="${targetdir}">
            <fileset dir="${sourcedir}">
                <exclude name="**/*.java"/>
            </fileset>
        </copy>
    </target>

    <target name="compile" depends="clean, copy-resources">
        <javac srcdir="${sourcedir}"
            destdir="${targetdir}"
            classpathref="libraries"/>
    </target>

    <target name="run" depends="compile">
        <java fork="true" classname="ergal.BusinessService" classpathref="libraries">
            <classpath path="${targetdir}"/>
            <arg value="${action}"/>
        </java>
    </target>
    <!-- create .java form  *.hbm.xml -->
    <target name="hbm2java" depends="compile"
        description="Generate Java source from the O/R mapping files">
        <taskdef name="hbm2java"
            classname="org.hibernate.tool.ant.HibernateToolTask"
            classpathref="project.class.path"/>
            <hbm2java destdir="${targetdir}">
                <configuration configurationfile="${targetdir}/hibernate.cfg.xml" /> 
                <hbm2java  jdk5="true"/>
                <!-- <cfg2hbm/> -->
            </hbm2java> 
   
    </target>
   
    <!-- create ddl form  *.hbm.xml -->
    <target name="hbm2ddl" depends="compile"
            description="Generate DB schema from the O/R mapping files">
        <taskdef name="hbm2ddl"
            classname="org.hibernate.tool.ant.HibernateToolTask"
            classpathref="project.class.path"/>
        <hbm2ddl destdir="${schema.dir}">
            <configuration configurationfile="${targetdir}/hibernate.cfg.xml" />
            <hbm2ddl export="true" console="false" create="true" update="false" drop="false" outputfilename="ahtest.sql"/>
        </hbm2ddl>  
    </target>

</project>


其中的 target name="hbm2java"  就是这次用来产生代码的任务

然后用cmd进入你的build.xml的根目录

运行ant hbm2java

会在你的根目录下多了一个bin文件夹里面就自动产生了一个project的源文件

包含以下代码

Customer.java

package ergal;
// Generated 2006-8-15 2:26:03 by Hibernate Tools 3.2.0.beta6a


import java.util.HashSet;
import java.util.Set;

/**
* Customer generated by hbm2java
*/
public class Customer  implements java.io.Serializable {

    // Fields   

     private long id;
     private String name;
     private Set<Order> orders = new HashSet<Order>(0);

     // Constructors

    /** default constructor */
    public Customer() {
    }

    /** full constructor */
    public Customer(String name, Set<Order> orders) {
       this.name = name;
       this.orders = orders;
    }
   
  
    // Property accessors
    public long getId() {
        return this.id;
    }
   
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
   
    public void setName(String name) {
        this.name = name;
    }
    public Set<Order> getOrders() {
        return this.orders;
    }
   
    public void setOrders(Set<Order> orders) {
        this.orders = orders;
    }




}



Order.java



package ergal;
// Generated 2006-8-15 2:26:03 by Hibernate Tools 3.2.0.beta6a



/**
* Order generated by hbm2java
*/
public class Order  implements java.io.Serializable {

    // Fields   

     private long id;
     private String orderNumber;
     private Customer customer;

     // Constructors

    /** default constructor */
    public Order() {
    }

    /** minimal constructor */
    public Order(Customer customer) {
        this.customer = customer;
    }
    /** full constructor */
    public Order(String orderNumber, Customer customer) {
       this.orderNumber = orderNumber;
       this.customer = customer;
    }
   
  
    // Property accessors
    public long getId() {
        return this.id;
    }
   
    public void setId(long id) {
        this.id = id;
    }
    public String getOrderNumber() {
        return this.orderNumber;
    }
   
    public void setOrderNumber(String orderNumber) {
        this.orderNumber = orderNumber;
    }
    public Customer getCustomer() {
        return this.customer;
    }
   
    public void setCustomer(Customer customer) {
        this.customer = customer;
    }




}





2 hbm2ddl

现在用映射文件来产生ddl和数据表

现在数据库里create database ahtest;

然后在根目录下运行

ant hbm2ddl(因为前面的build.xml里已经定义了hbm2ddl --“target name="hbm2ddl" ”)

就会在数据库的ahtest里自动建好了customers和orders两个表

还会在data文件夹下产生

ahtest.sql这个ddl文件



create table CUSTOMERS (
    ID bigint not null,
    NAME varchar(15),
    primary key (ID));
create table ORDERS (
    ID bigint not null,
    ORDERNUMBER varchar(15),
    CUSTOMER_ID bigint not null,
    primary key (ID));
alter table ORDERS
    add index FK8B7256E5479EC1E3 (CUSTOMER_ID),
    add constraint FK8B7256E5479EC1E3 foreign key (CUSTOMER_ID) references CUSTOMERS (ID);



这就是hbm2java和hbm2ddl这两个方便的工具的基本用法


你可能感兴趣的:(eclipse,Hibernate,xml,mysql,ant)