[原创]Pro Hibernate 3笔记和小结(9)之第三章创建简单应用

/**
作者:Willpower
来源:Rifoo Technology(
http://www.rifoo.com
时间:2006-07
备注:转载请保留以上声明
**/

本节通过实例来讲解运行Message of The Day范例程序。

当Hibernate和数据库都已经安装,并且配置文件已经创建后,我们要做的是创建类。下面我们来完整的看一下这些类的全部内容(第一章中为了简单介绍而对这些类忽略了大量细节):

Listing 3-5. Motd POJO类
CODE:

public class Motd {
  protected Motd() {
  }
  public Motd(int id, String message) {
    this.id = id;
    this.message = message;
  }

  public int getId() {
    return id;
  }
  public String getMessage() {
    return message;
  }
  public void setId(int id) {
    this.id = id;
  }
  public void setMessage(String message) {
    this.message = message;
  }
  private int id;
  private String message;
}


下面,我们创建一个自定义异常类MotdException,它扩展了Exception类,它作为持久层抛出的所有异常的一个容器。

Listing 3-6. MotdException类
CODE:

public class MotdException extends Exception {
  public MotdException(String message) {
    super(message);
  }
  public MotdException(String message, Throwable cause) {
    super(message, cause);
  }

}

最后,我们来看一看本应用的核心代码:

Listing 3-7.Motd Application
CODE:

import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateMotd {
  public static void main(String[] args) {
    if (args.length != 1) {
        System.err.println("Nope, enter one message number");
    } else {
        try {
          int messageId = Integer.parseInt(args[0]);
          Motd motd = getMotd(messageId);
          if (motd != null) {
            System.out.println(motd.getMessage());
          } else {
            System.out.println("No such message");
          }
      } catch (NumberFormatException e) {
            System.err.println("You must enter an integer - " + args[0]
                                + " won't do.");
      } catch (MotdException e) {
            System.err.println("Couldn't get the message: " + e);
      }
    }
  }
  public static Motd getMotd(int messageId)
      throws MotdException
  {
    SessionFactory sessions =
        new Configuration().configure().buildSessionFactory();
    Session session = sessions.openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        Motd motd = (Motd)session.get(Motd.class, new Integer(messageId));
        tx.commit();
        tx = null;
        return motd;
    } catch ( HibernateException e ) {
        if ( tx != null ) tx.rollback();
        log.log(Level.SEVERE, "Could not acquire message", e);
        throw new MotdException(
          "Failed to retrieve message from the database.",e);
    } finally {
        session.close();
    }
  }
  private static final Logger log = Logger.getAnonymousLogger();
}


要将这些类自动的构建并打包为一个jar文件,我们编写一个ANT build.xml文件:

Listing 3-8. Motd Ant Build脚本
CODE:

<project default="all">

  <property name="hibernate" location="/home/hibernate-3.0" />
  <property name="jdbc" location="/home/hsqldb/lib/hsqldb.jar " />

  <property name="src" location="." />
  <property name="config" location="." />
  <property name="bin" location="bin" />
  <property name="name" value="motd"/>

  <path id="classpath.base">
    <pathelement location="${bin}" />
    <pathelement location="${hibernate}/hibernate3.jar" />
    <fileset dir="${hibernate}/lib" includes="**/*.jar" />
    <pathelement location="${jdbc}" />
  </path>

  <path id="classpath.run">
    <pathelement location="${config}" />
    <path refid="classpath.base" />
  </path>

  <target name="init">
    <mkdir dir="${bin}" />
  </target>

  <target name="compile" depends="init">
    <javac srcdir="${src}" destdir="${bin}">
        <classpath refid="classpath.base" />
    </javac>
  </target>

  <target name="dist">
    <jar destfile="${name}.jar"
      basedir="${bin}"
        />
  </target>

  <target name="clean">
    <delete dir="${bin}" />
    <delete file="${name}.jar"/>
  </target>

  <target name="all" depends="dist" />
</project>


运行ant,将生成一个Message of The Day应用程序的jar包,命名为motd.jar。

下一个步骤是创建数据库,这个可以手工进行。当然,生成SQL来创建数据库有利于确认映射文件和数据模型是否能正确的对应上。
为了提高可读性,我们为范例设置CLASSPATH环境变量,可以在window中设置,也可以通过-classpath参数来设置,也可以在ant脚本中加一个任务来设置。
classpath应该包括:Hibernate3.jar
还有以下它的支持包:
commons-logging-1.0.4.jar
cglib-full-2.0.2.jar
commons-collections-2.1.1.jar
antlr-2.7.4.jar
dom4j-1.5.2.jar
ehcache-1.1.jar
jta.jar

还需要包括jdbc驱动包,本范例中使用hsqldb.jar。

构建schma的命令如下:
java org.hibernate.tool.hbm2ddl.SchemaExport --text --output=motd.sql
--config=hibernate.cfg.xml

SQL语句将被写到motd.sql文件中。这样,我们可以使用这个文件来创建数据库。这个时候,我们可以运行应用程序了,但是数据库里没有任何数据。

运行:java HibernateMotd 1

返回:No such message

现在我们手工插入一条数据到数据库,使用脚本
insert into motd (id,message) values (1,'Hello World')
我们再次运行java HibernateMotd 1
返回:Hello World

总结,运行这个范例包含了三个步骤:
1 创建Hibernate配置文件
2 创建mapping文件
3 编写POJO类
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值