整合Hibernate2.1.6到JBoss3.2.5

类别:Java 点击:0 评论:0 推荐:

先决条件:
1、开发工具Eclipse安装了插件Lomboz,并指明Server为JBoss
2、已经在Jboss中建立了与MySql的DataSource连接,JNDI为 java:/MySqlDS
3、已经在MySql中建立了表 CAT
Column |         Type          | Modifiers
--------+-----------------------+-----------
cat_id | character(32)         | not null
name   | character varying(16) | not null
sex    | character(1)          |
weight | real                  |
Indexes: cat_pkey primary key btree (cat_id)

整合步骤:
1、生成一个WEB应用
2、在这个应用的WEB-INF\lib下应该包含以下Hibernate必需包
hibernate2.jar
odmg-3.0.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
dom4j-1.4.jar
ehcache-0.9.jar
cglib-full-2.0.2.jar
3、在这个应用的WEB-INF\classes下生成Hibernate配置文件hibernate.cfg.xml(也可以用hibernate.properties,此处不议),内容如下:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration
    PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
    <session-factory name="hibernate/SessionFactory">
        <property name="connection.datasource">java:/MySqlDS</property>
        <property name="show_sql">true</property>
        <property name="dialect">hibernate.dialect net.sf.hibernate.dialect.MySQLDialect</property>

         <!-- Mapping files -->
        <mapping resource="Cat.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

hibernate/SessionFactory为你需要绑定SessionFactory的JNDI名(绑定之后可以在容器内用Context lookup)。
java:/MySqlDS为你已经绑定好的MySql DataSource名。
hibernate.dialect net.sf.hibernate.dialect.MySQLDialect为Hibernate指明数据库方言为MYSQL。
Cat.hbm.xml为Hibernate映射文件,下面会提到。

4、定义可持久化类(POJO)-- Cat.java
public class Cat {   
private String id;
    private String name;
    private char sex;
    private float weight;
    public Cat() {
    }
    public String getId() {
        return id;
    }
   public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public char getSex() {
        return sex;
    }
   public void setSex(char sex) {
        this.sex = sex;
    }
    public float getWeight() {
        return weight;
    }
   public void setWeight(float weight) {
        this.weight = weight;
    }
}

5、定义类映射文件-- Cat.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping
    PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>

    <class name="com.pbmaster.study.hibernate.po.Cat" table="CAT">

        <!-- A 32 hex character is our surrogate key. It's automatically
            generated by Hibernate with the UUID pattern. -->
        <id name="id" type="string" unsaved-value="null" >
            <column name="CAT_ID" sql-type="char(32)" not-null="true"/>
            <generator class="uuid.hex"/>
        </id>

        <!-- A cat has to have a name, but it shouldn' be too long. -->
        <property name="name">
            <column name="NAME" sql-type="varchar(16)" not-null="true"/>
        </property>

        <property name="sex"/>

        <property name="weight"/>

    </class>

</hibernate-mapping>

此xml文件放置到hibernate.cfg.xml相同的目录(不知道放到其他地方行不行,待查)。

6、定义一个startup Servlet -InitHibernate.java,在Servlet的init()中启动Hibernate,并绑定JNDI
public class InitHibernate extends HttpServlet {

 public void init(ServletConfig config) throws ServletException {
  super.init(config);
  try{
   SessionFactory sf = new Configuration().configure().buildSessionFactory();
      System.out.println("Hibernate Startup completed successfully");
  }
  catch(Exception ex){
   ex.printStackTrace();
  }
  //TODO Method stub generated by Lomboz
 }

 public void service(ServletRequest request, ServletResponse response)
   throws ServletException, IOException {
  //TODO Method stub generated by Lomboz
 }
}

为了能让这个Servlet能在服务器启动时被运行,需要配置WEB.XML文件:
 <servlet>
  <servlet-name>inithibernate</servlet-name>
  <display-name>inithibernate</display-name>
  <servlet-class>com.pbmaster.study.hibernate.servlet.InitHibernate</servlet-class>
  <load-on-startup>10</load-on-startup>
 </servlet>

7、OK,部署这个WEB应用,启动JBOSS!如果在JBOSS的控制台打出的信息中没有Exception信息,那么就成功。
根据Hibernate文档的介绍,也可以用另一种方式,就是定义一个HibernateUtil类,调用这个类的静态方法currentSession一次。其实这2种方法基本一样,都能达到效果。

8、测试HIBERNATE
定义一个Servlet,其service()中有如下代码:

   Context ctx=new InitialContext();
   sf = (SessionFactory) ctx.lookup("hibernate/SessionFactory");
   Session session=sf.openSession();
   Transaction tx= session.beginTransaction();

   Cat princess = new Cat();
   princess.setName("Princess");
   princess.setSex('F');
   princess.setWeight(7.4f);

   session.save(princess);
   tx.commit();
   session.close();

如果没有异常,数据库当中应该已经有了一条数据!

再来一个jsp做查询的例子:
<!-- Copyright (c) 2002 by ObjectLearn. All Rights Reserved. -->
<%@ page import="javax.naming.*"%>
<%@ page import="net.sf.hibernate.*"%>
<%@ page import="java.util.*"%>
<%@ page import="com.catmiw.hibernate.study.po.*"%>


<%
    try {
     Context ctx = new InitialContext();  //得到初始化上下文

     SessionFactory sf = (SessionFactory) ctx.lookup("hibernate/SessionFactory");
     Session sess=sf.openSession();
     
      String temp;
       System.out.println("Success connect Hibernate!");

  Query query = sess.createQuery("select cat from Cat as cat where cat.sex = :sex");
  
  query.setCharacter("sex", 'F');
  for (Iterator it = query.iterate(); it.hasNext();) {
      Cat cat = (Cat) it.next();
      temp = cat.getName() ;

%>

<html>
 <head>
   <title>Welcome</title>
 </head>
 <body>
  <center>name is : <%=temp%></center>
 
 </body>
</html>
<%
      }
      sess.close();
    }
    catch (Exception e) {
      System.out.print("get data error!");
      e.printStackTrace();
    }
%>

从显示的SQL语句看,当查询一个结果集时,HIBERNATE是先把满足条件的记录的主键取出来,再一条一条按主键去取。
(看后当场昏倒,吐血......,变吐血还在边问“为什么这样.......,这样不是效率太低了吗?? ”)


本文地址:http://com.8s8s.com/it/it14414.htm