zoukankan      html  css  js  c++  java
  • Hibernate Tomcat JNDI数据源配置(转)

    简述:

    配置JNDI 查找Tomcat 中server.xml中定义的数据源

    步骤:

    1. 修改elipse的数据源server.xml

    主要修改如下,

    1. 添加下面这段Context文本 其中StudentManagementWeb是项目名称

    1.     <Context docBase="StudentManagementWeb" path="/StudentManagementWeb" reloadable="true" source="org.eclipse.jst.jee.server:StudentManagementWeb">  
    2.         <Resource name="jdbc/smw" auth="Container" type="javax.sql.DataSource"  
    3. maxActive="100" maxIdle="30" maxWait="10000"  
    4. username="root" password="sql" driverClassName="com.mysql.jdbc.Driver"  
    5. url="jdbc:mysql://localhost:3306/smw"/>  
    6.     </Context>  

    2.修改项目的web.xml文件

    添加如下字段,用来查找数据源

    [plain] view plaincopy
    1.  <resource-ref>  
    2. <description>DB Connection</description>  
    3. <res-ref-name>jdbc/smw</res-ref-name>  
    4. <res-type>javax.sql.DataSource</res-type>  
    5. <res-auth>Container</res-auth>  
    6.  </resource-ref>  

    3. 修改Hibernate配置文件,其中 mapping resourse 为自定义的model对象

    1. <session-factory>  
    2.     <property name="connection.datasource">java:comp/env/jdbc/smw</property>  
    3.         <property name="dialect">  
    4.         org.hibernate.dialect.MySQLDialect  
    5.     </property>  
    6.     <property name="show_sql">true</property><!-- show sql statement -->  
    7.     <!-- mapping files -->  
    8.     <mapping resource="smw/model/Student.hbm.xml"/>  
    9.     <mapping resource="smw/model/CourseSelection.hbm.xml"/>  
    10.     <mapping resource="smw/model/Course.hbm.xml"/>  
    11. </session-factory>  

    4. Hibernate的session builder

    [plain] view plaincopy
    1. Configuration cfg = new Configuration().configure();  
    2. factory = cfg.buildSessionFactory();   //build Session Factory  

    完成上述四步就做到了JNDI查找数据源的配置了

    下面是四个文件的完整代码

    server.xml

    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <!--  
    3.   Licensed to the Apache Software Foundation (ASF) under one or more  
    4.   contributor license agreements.  See the NOTICE file distributed with  
    5.   this work for additional information regarding copyright ownership.  
    6.   The ASF licenses this file to You under the Apache License, Version 2.0  
    7.   (the "License"); you may not use this file except in compliance with  
    8.   the License.  You may obtain a copy of the License at  
    9.   
    10.       http://www.apache.org/licenses/LICENSE-2.0  
    11.   
    12.   Unless required by applicable law or agreed to in writing, software  
    13.   distributed under the License is distributed on an "AS IS" BASIS,  
    14.   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
    15.   See the License for the specific language governing permissions and  
    16.   limitations under the License.  
    17. --><!-- Note:  A "Server" is not itself a "Container", so you may not  
    18.      define subcomponents such as "Valves" at this level.  
    19.      Documentation at /docs/config/server.html  
    20.  --><Server port="8005" shutdown="SHUTDOWN">  
    21.   
    22.   <!--APR library loader. Documentation at /docs/apr.html -->  
    23.   <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>  
    24.   <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->  
    25.   <Listener className="org.apache.catalina.core.JasperListener"/>  
    26.   <!-- Prevent memory leaks due to use of particular java/javax APIs-->  
    27.   <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>  
    28.   <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->  
    29.   <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>  
    30.   <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>  
    31.   
    32.   <!-- Global JNDI resources  
    33.        Documentation at /docs/jndi-resources-howto.html  
    34.   -->  
    35.   <GlobalNamingResources>  
    36.     <!-- Editable user database that can also be used by  
    37.          UserDatabaseRealm to authenticate users  
    38.     -->  
    39.     <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>  
    40.   </GlobalNamingResources>  
    41.   
    42.   <!-- A "Service" is a collection of one or more "Connectors" that share  
    43.        a single "Container" Note:  A "Service" is not itself a "Container",   
    44.        so you may not define subcomponents such as "Valves" at this level.  
    45.        Documentation at /docs/config/service.html  
    46.    -->  
    47.   <Service name="Catalina">  
    48.     
    49.     <!--The connectors can use a shared executor, you can define one or more named thread pools-->  
    50.     <!--  
    51.     <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"   
    52.         maxThreads="150" minSpareThreads="4"/>  
    53.     -->  
    54.       
    55.       
    56.     <!-- A "Connector" represents an endpoint by which requests are received  
    57.          and responses are returned. Documentation at :  
    58.          Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)  
    59.          Java AJP  Connector: /docs/config/ajp.html  
    60.          APR (HTTP/AJP) Connector: /docs/apr.html  
    61.          Define a non-SSL HTTP/1.1 Connector on port 8080  
    62.     -->  
    63.     <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>  
    64.     <!-- A "Connector" using the shared thread pool-->  
    65.     <!--  
    66.     <Connector executor="tomcatThreadPool"  
    67.                port="8080" protocol="HTTP/1.1"   
    68.                connectionTimeout="20000"   
    69.                redirectPort="8443" />  
    70.     -->             
    71.     <!-- Define a SSL HTTP/1.1 Connector on port 8443  
    72.          This connector uses the JSSE configuration, when using APR, the   
    73.          connector should be using the OpenSSL style configuration  
    74.          described in the APR documentation -->  
    75.     <!--  
    76.     <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"  
    77.                maxThreads="150" scheme="https" secure="true"  
    78.                clientAuth="false" sslProtocol="TLS" />  
    79.     -->  
    80.   
    81.     <!-- Define an AJP 1.3 Connector on port 8009 -->  
    82.     <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>  
    83.   
    84.   
    85.     <!-- An Engine represents the entry point (within Catalina) that processes  
    86.          every request.  The Engine implementation for Tomcat stand alone  
    87.          analyzes the HTTP headers included with the request, and passes them  
    88.          on to the appropriate Host (virtual host).  
    89.          Documentation at /docs/config/engine.html -->  
    90.   
    91.     <!-- You should set jvmRoute to support load-balancing via AJP ie :  
    92.     <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">           
    93.     -->   
    94.     <Engine defaultHost="localhost" name="Catalina">  
    95.   
    96.       <!--For clustering, please take a look at documentation at:  
    97.           /docs/cluster-howto.html  (simple how to)  
    98.           /docs/config/cluster.html (reference documentation) -->  
    99.       <!-- 
    100.       <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> 
    101.       -->          
    102.   
    103.       <!-- The request dumper valve dumps useful debugging information about  
    104.            the request and response data received and sent by Tomcat.  
    105.            Documentation at: /docs/config/valve.html -->  
    106.       <!-- 
    107.       <Valve className="org.apache.catalina.valves.RequestDumperValve"/> 
    108.       -->  
    109.   
    110.       <!-- This Realm uses the UserDatabase configured in the global JNDI  
    111.            resources under the key "UserDatabase".  Any edits  
    112.            that are performed against this UserDatabase are immediately  
    113.            available for use by the Realm.  -->  
    114.       <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>  
    115.   
    116.       <!-- Define the default virtual host  
    117.            Note: XML Schema validation will not work with Xerces 2.2.  
    118.        -->  
    119.       <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false">  
    120.   
    121.         <!-- SingleSignOn valve, share authentication between web applications  
    122.              Documentation at: /docs/config/valve.html -->  
    123.         <!-- 
    124.         <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> 
    125.         -->  
    126.   
    127.         <!-- Access log processes all example.  
    128.              Documentation at: /docs/config/valve.html -->  
    129.         <!--  
    130.         <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"    
    131.                prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>  
    132.         -->  
    133.   
    134.       <Context docBase="StudentManagementWeb" path="/StudentManagementWeb" reloadable="true" source="org.eclipse.jst.jee.server:StudentManagementWeb">  
    135.         <Resource name="jdbc/smw" auth="Container" type="javax.sql.DataSource"  
    136.         maxActive="100" maxIdle="30" maxWait="10000"  
    137.         username="root" password="sql" driverClassName="com.mysql.jdbc.Driver"  
    138.         url="jdbc:mysql://localhost:3306/smw"/>  
    139.       </Context>  
    140.       </Host>  
    141.     </Engine>  
    142.   </Service>  
    143. </Server>  


    web.xml

    [plain] view plaincopy
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
    3.   <display-name>StudentManagementWeb</display-name>  
    4.   <welcome-file-list>  
    5.     <welcome-file>Login.jsp</welcome-file>  
    6.   </welcome-file-list>  
    7.     
    8.   <resource-ref>  
    9.     <description>DB Connection</description>  
    10.     <res-ref-name>jdbc/smw</res-ref-name>  
    11.     <res-type>javax.sql.DataSource</res-type>  
    12.     <res-auth>Container</res-auth>  
    13.   </resource-ref>  
    14.     
    15.   <context-param>   
    16.     <param-name>log4jConfigLocation</param-name>   
    17.     <param-value>/WEB-INF/log4j.properties</param-value>   
    18.   </context-param>   
    19.     
    20.   <!-- Define LOG4J Listener -->   
    21.   <listener>   
    22.    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>   
    23.   </listener>   
    24.     
    25.   <servlet>  
    26.   <!-- define the name of Servlet -->  
    27.   <servlet-name>dispatcherServlet</servlet-name>  
    28.   <!-- Servlet implementation class -->  
    29.   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    30.   <!-- initialize the context -->  
    31.   <init-param>  
    32.   <param-name>contextConfigLocation</param-name>  
    33.   <!-- load configuration -->  
    34.   <param-value>/WEB-INF/applicationContext.xml</param-value>  
    35.   </init-param>  
    36.   <!-- set loading priority -->  
    37.   <load-on-startup>1</load-on-startup>  
    38.   </servlet>  
    39.   <servlet-mapping>  
    40.   <servlet-name>dispatcherServlet</servlet-name>  
    41.   <url-pattern>*.do</url-pattern>  
    42.   </servlet-mapping>  
    43.     
    44. </web-app>  


    hibernate.cfg.xml

    1. <?xml version='1.0' encoding='UTF-8'?>  
    2. <!DOCTYPE hibernate-configuration PUBLIC  
    3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
    4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
    5.   
    6. <hibernate-configuration>  
    7.   
    8.     <session-factory>  
    9. <!--         <property name="dialect">Database Dialect  
    10.             org.hibernate.dialect.MySQLDialect  
    11.         </property>  
    12.         <property name="connection.url">URL of the database  
    13.             jdbc:mysql://localhost:3306/smw  
    14.         </property>  
    15.         <property name="connection.username">root</property>user name  
    16.         <property name="connection.password">sql</property>password  
    17.         <property name="connection.driver_class">connect driver  
    18.             com.mysql.jdbc.Driver  
    19.         </property> -->  
    20.         <property name="connection.datasource">java:comp/env/jdbc/smw</property>  
    21.         <property name="dialect">  
    22.             org.hibernate.dialect.MySQLDialect  
    23.         </property>  
    24.         <property name="show_sql">true</property><!-- show sql statement -->  
    25.         <!-- mapping files -->  
    26.         <mapping resource="smw/model/Student.hbm.xml"/>  
    27.         <mapping resource="smw/model/CourseSelection.hbm.xml"/>  
    28.         <mapping resource="smw/model/Course.hbm.xml"/>  
    29.     </session-factory>  
    30.   
    31. </hibernate-configuration>  


    HibernateUtil.java

      1. package smw.utils;  
      2.   
      3. import org.hibernate.Session;  
      4. import org.hibernate.SessionFactory;  
      5. import org.hibernate.cfg.Configuration;  
      6.   
      7. public class HibernateUtil {  
      8.     private static SessionFactory factory;  
      9.     static{  
      10.         try{  
      11.             Configuration cfg = new Configuration().configure();  
      12.             factory = cfg.buildSessionFactory();   //build Session Factory  
      13.         }catch(Exception e){  
      14.             System.out.println("static of HibernateUtil: " + e.getMessage());  
      15.         }  
      16.     }  
      17.       
      18.     /** 
      19.      * @return SessionFactory 
      20.      */  
      21.     public static SessionFactory getSessionFactory(){  
      22.         return factory;  
      23.     }  
      24.       
      25.     /** 
      26.      * get Session 
      27.      * @return Session 
      28.      */  
      29.     public static Session getSession(){  
      30.         return factory.openSession();  
      31.     }  
      32.       
      33.     /** 
      34.      * close Session 
      35.      * @param session 
      36.      */  
      37.     public static void closeSession(Session session){  
      38.         if(session != null){  
      39.             if(session.isOpen()){  
      40.                 session.close();  
      41.             }  
      42.         }  
      43.     }  
      44. }  


    http://blog.csdn.net/anialy/article/details/8237448

  • 相关阅读:
    WordPress后台添加侧边栏菜单
    Redis 使用多个数据库及密码配置
    datatable 修改点击列头进行排序顺序
    命令行客户端操作pg数据库常用操作
    pg 创建自增id
    让 PHP COOKIE 立即生效(不用刷新就可以使用)
    js cookie
    使用mysql监视器即命令行下的mysql
    javascript 获取键盘上的按键代码KeyCode
    吞吐量(TPS)、QPS、并发数、响应时间(RT)概念
  • 原文地址:https://www.cnblogs.com/softidea/p/4486121.html
Copyright © 2011-2022 走看看