论坛首页 Java企业应用论坛

[原创]在虚拟主机上让Jive论坛和Hibernate共享一个数据库连接池

浏览 4408 次
该帖已经被评为精华帖
作者 正文
   发表时间:2004-03-04  
背景:在一台虚拟主机上(TOMCAT)已经运行了jive论坛(使用自带的数据库连接池),现在想在此虚拟主机上安装Hibernate.
问题:由于jive和Hibernate都需要使用数据库连接池,如何让它们共享一个连接池。

一种解决办法:
由于jive和Hibernate都支持通过JNDI来查找一个连接池实例,因此为虚拟主机配置一个数据库连接池并把它绑定到JNDI上即可。由于虚拟主机都禁止每个用户修改server.xml文件,因此通过编辑server.xml来给虚拟主机配置数据库连接池行不通。那么我们可以编写一个启动就自动加载的Servlet,在其中配置连接池并把它绑定到JNDI上。
这里连接池我使用了TOMCAT自带的DBCP,数据库使用mysql.

先编写一个servlet负责初始化DBCP
package myDataSource;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.naming.*;
import org.apache.commons.dbcp.*;

public class JndiDataSourceServlet extends HttpServlet{

public void init(ServletConfig config); throws ServletException
{
   String DBUrl = config.getInitParameter("DBUrl");;
   if(DBUrl == null); DBUrl = "jdbc:mysql://localhost/jive";

   String Username = config.getInitParameter("Username");;
   if(Username == null); Username = "root";

   String Password = config.getInitParameter("Password");;
   if(Password == null); Password = "root";

   String DriverClassName = config.getInitParameter("DriverClassName");;
   if(DriverClassName == null); DriverClassName = "org.gjt.mm.mysql.Driver";

   String MaxWaitStr = config.getInitParameter("MaxWait");;
   if(MaxWaitStr == null); MaxWaitStr = "3000";
   long MaxWait = (new Long(MaxWaitStr););.longValue();;

   String MaxIdleStr = config.getInitParameter("MaxIdle");;
   if(MaxIdleStr == null); MaxIdleStr = "10";
   int MaxIdle = (new Integer(MaxIdleStr););.intValue();;

   String MaxActiveStr = config.getInitParameter("MaxActive");;
   if(MaxActiveStr == null); MaxActiveStr = "100";
   int MaxActive = (new Integer(MaxActiveStr););.intValue();;
            
   String JndiName = config.getInitParameter("JndiName");;
   if(JndiName == null); JndiName = "my_datasource";
            
try{
 Context initCtx = (Context);new InitialContext();;
 BasicDataSource bds = new BasicDataSource();;

 bds.setUrl(DBUrl);;
 bds.setUsername(Username);;
 bds.setPassword(Password);;
 bds.setDriverClassName(DriverClassName);;
 bds.setMaxWait(MaxWait);;
 bds.setMaxIdle(MaxIdle);;
 bds.setMaxActive(MaxActive);;
 initCtx.rebind(JndiName,bds);;

}catch(Exception e);{
  e.printStackTrace();;
}

}//end init(ServletConfig config);

}//end JndiDataSourceServlet


之后再修改虚拟主机的web.xml,类似如下
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <display-name>Tomcat Examples</display-name>
    <description>
      Tomcat Example servlets and JSP pages.
    </description>

    <servlet>
        <servlet-name>jndiSource</servlet-name>
        <servlet-class>myDataSource.JndiDataSourceServlet</servlet-class>
        <init-param>
            <param-name>DBUrl</param-name>
            <param-value>jdbc:mysql://localhost/jive</param-value>
        </init-param>
        <init-param>
            <param-name>Username</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <param-name>Password</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <param-name>DriverClassName</param-name>
            <param-value>org.gjt.mm.mysql.Driver</param-value>
        </init-param>
        <init-param>
            <param-name>MaxWait</param-name>
            <param-value>3000</param-value>
        </init-param>
        <init-param>
            <param-name>MaxIdle</param-name>
            <param-value>10</param-value>
        </init-param>
        <init-param>
            <param-name>MaxActive</param-name>
            <param-value>100</param-value>
        </init-param>
        <init-param>
            <param-name>JndiName</param-name>
            <param-value>my_datasource</param-value>
        </init-param>

        <load-on-startup>1</load-on-startup>
    </servlet>


</web-app>
   发表时间:2004-03-04  
之后再把Hibernate文档中的例子--Cat 附在这里:
1、先把Hibernate.hbm.xml和Cat.hbm.xml拷贝到classes目录中。
Hibernate.hbm.xml文件:
<?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>

        <property name="connection.datasource">my_datasource</property>
        <property name="show_sql">true</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>

        <!-- Mapping files -->
        <mapping resource="Cat.hbm.xml"/>

    </session-factory>

</hibernate-configuration>


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="mytest.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>


Cat.java
package mytest;

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;
    }

}


HibernateUtil.java
package mytest;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration();.configure();.buildSessionFactory();;
        } catch (HibernateException ex); {
            throw new RuntimeException("Exception building SessionFactory: " + ex.getMessage();, ex);;
        }
    }

    public static final ThreadLocal session = new ThreadLocal();;

    public static Session currentSession(); throws HibernateException {
        Session s = (Session); session.get();;
        // Open a new Session, if this Thread has none yet
        if (s == null); {
            s = sessionFactory.openSession();;
            session.set(s);;
        }
        return s;
    }

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


最后是一个测试用的test.jsp文件
<%@ page contentType="text/html;CHARSET=utf8"%>
<%@ page import= "net.sf.hibernate.* "%>
<%@ page import= "mytest.* "%>
<%@ page import= "java.sql.* "%>
<%@ page import= "javax.naming.* "%>
<%@ page import= "org.apache.commons.dbcp.* "%>

<%
        try{

//test jiveUser table first.

          Context initCtx = new InitialContext();;
          Object obj = (Object); initCtx.lookup("my_datasource");;    
          javax.sql.DataSource ds = (javax.sql.DataSource);obj;

          Connection conn = ds.getConnection();;
          Statement  stmt = conn.createStatement();;
          String strSql = " select userID,name from jiveUser ";
                      
          ResultSet rs = stmt.executeQuery(strSql);;
              while(rs.next(););{
	          out.println(rs.getString(1););;                 
        	  out.println(rs.getString(2););;
          		}
               }catch(Exception ex);{
                ex.printStackTrace();;
               }
         



//test Hibernate.

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


Session session1 = HibernateUtil.currentSession();;

Transaction tx= session1.beginTransaction();;
session1.save(princess);;
tx.commit();;

HibernateUtil.closeSession();;

    
%>
<hr>



到此为止,在虚拟主机上配置和测试Hibernate的工作基本完成了。以上代码在Tomcat上均测试通过。
另外我刚刚接触Hibernate,如果配置或代码中有不合理的地方,烦请大家指点。
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics