Hibernate + Tomcat + MySql

0

Witam,
mam dość spory problem ze skonfigurowaniem środowiska na podstawie zarówno swoich własnych prostych aplikacji jak i przykładowych. Szukałem informacji w Sieci, aczkolwiek mimo stosowania się do zalecanych rad nie udało mi się rozwiązać problemu. Do sedna jednak... Aplikacja jest wyjątkowo prosta i opiera się na formularzu, który dodaje nowy wpis do bazy danych. Po próbie nawiązania połączenia do bazy danych otrzymuję następujący ST:

Cannot open connection org.hibernate.exception.ErrorCodeConverter.handledNonSpecificException(ErrorCodeConverter.java:92) org.hibernate.exception.ErrorCodeConverter.convert(ErrorCodeConverter.java:80) org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29) org.hibernate.jdbc.AbstractBatcher.openConnection(AbstractBatcher.java:427) org.hibernate.jdbc.JDBCContext.connect(JDBCContext.java:168) org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:103) org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:49) org.hibernate.transaction.JDBCTransactionFactory.beginTransaction(JDBCTransactionFactory.java:24) org.hibernate.jdbc.JDBCContext.beginTransaction(JDBCContext.java:231) org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1073) com.UserDAO.saveUser(Unknown Source) com.UserController.onSubmit(Unknown Source) org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:332) org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:307) org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:248) org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:243) org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:128) org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:44) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:684) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:625) org.springframework.web.servlet.FrameworkServlet.serviceWrapper(FrameworkServlet.java:386) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:355) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) java.lang.Thread.run(Thread.java:679)

test-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

   <bean id="userFormValidator" class="com.UserFormValidator"/>

   	<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
		<property name="url"><value>jdbc:mysql://localhost:3306/techfaq</value></property>
		<property name="username"><value>techfaq</value></property>
		<property name="password"><value>techfaq</value></property>
	</bean>

	<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource"><ref bean="myDataSource"/></property>
		<property name="mappingResources">
			<list>
				<value>/com/user.hbm.xml</value>
			</list>
		</property>
		<property name="hibernateProperties">
			<value>
				hibernate.dialect=org.hibernate.dialect.MySQLDialect
			</value>
		</property>
	</bean>
	
	<bean id="userdao" class="com.UserDAO">
		<property name="sessionFactory"><ref bean="mySessionFactory"/></property>
	</bean>  

   	<bean id="userController" class="com.UserController">
      	<property name="sessionForm"><value>true</value></property>        
      	<property name="commandName"><value>userBean</value></property> 
      	<property name="commandClass"><value>com.UserBean</value></property>   
      	<property name="validator"><ref bean="userFormValidator"/></property>
      	<property name="formView"><value>userForm</value></property>
      	<property name="successView"><value>success</value></property>
      	<property name="userdao"><ref bean="userdao"/></property>
   	</bean>
    
	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="urlMap">
			<map>
				<entry key="/test/userPage.do"><ref bean="userController"/></entry>
			</map>
		</property>
	</bean>
    
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property>
        <property name="prefix"><value>/WEB-INF/jsp/</value></property>
        <property name="suffix"><value>.jsp</value></property>
    </bean>
	
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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 id="WebApp">
	<display-name>techfaq</display-name>
	
	<servlet>
		<servlet-name>test</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>test</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

	<taglib>
		<taglib-uri>/spring</taglib-uri>
		<taglib-location>/WEB-INF/spring.tld</taglib-location>
	</taglib>

</web-app>

user.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
		"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="com.UserBean" table="USER_TEST">
		<id name="userId" column="USER_ID" type="int">
            <generator class="native"/>
        </id>
       
        <property name="userName" column="user_name"/>
        <property name="deptName" column="dept_name"/>
    </class>

</hibernate-mapping>

UserController.java

package com;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;


public class UserController extends SimpleFormController{
	private UserDAO userdao;
	
	 public Object formBackingObject(HttpServletRequest request) throws ServletException
	   {
	 	UserBean backingObject = new UserBean();
	 	System.out.println("formBackingObject");

        return backingObject;
	   }
	   
	 public ModelAndView onSubmit(Object command) throws ServletException 
	 {
	 	UserBean user = (UserBean)command;
	 	System.out.println("username :"+user.getUserName());
	 	System.out.println("dept :"+user.getDeptName());
		String message = getUserdao().saveUser(user);
		ModelAndView webPage;
		if (message != null)
		{
		    webPage = new ModelAndView("db_error");
		    webPage.addObject("message", message);
		} else 
		{
		    webPage = new ModelAndView("success");
		    webPage.addObject("message", user.getUserName());
		}

        return webPage;
    }

	/**
	 * @return Returns the userdao.
	 */
	public UserDAO getUserdao() 
	{
		return userdao;
	}
	
	/**
	 * @param userdao The userdao to set.
	 */
	public void setUserdao(UserDAO userdao) 
	{
		this.userdao = userdao;
	}
}

UserDAO.java

package com;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import org.springframework.orm.hibernate.support.HibernateDaoSupport;


public class UserDAO {
	
	private SessionFactory sessionFactory;

	public UserDAO()
	{
	}

	public String saveUser(UserBean user)
	{
	    String message = null;
		Session session = getSessionFactory().openSession();
		try
		{
			Transaction tx = session.beginTransaction();
			session.save(user);
			tx.commit();
		}catch(Exception e){
			e.printStackTrace();
			StringBuilder sb = new StringBuilder();
            sb.append(e.getMessage());
            sb.append("\n");
            StackTraceElement[] stackTrace = e.getStackTrace();
            for (int i=0; i < stackTrace.length; i++)
            {
                sb.append(stackTrace[i]);
                sb.append("\n");
            }
            message = sb.toString();
		}finally{
			session.close();
		}
		
		return message;
	}
	

	/**
	 * @return Returns the sessionFactory.
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	/**
	 * @param sessionFactory The sessionFactory to set.
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}

tomcat/conf/context.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>
    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

</Context>

tomcat/conf/server.xml

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">

  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container", 
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">
  
    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" 
        maxThreads="150" minSpareThreads="4"/>
    -->
    
    
    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />
    -->           
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the 
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">         
    --> 
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->        

      <!-- The request dumper valve dumps useful debugging information about
           the request and response data received and sent by Tomcat.
           Documentation at: /docs/config/valve.html -->
      <!--
      <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
      -->

      <!-- This Realm uses the UserDatabase configured in the global JNDI
           resources under the key "UserDatabase".  Any edits
           that are performed against this UserDatabase are immediately
           available for use by the Realm.  -->
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>

      <!-- Define the default virtual host
           Note: XML Schema validation will not work with Xerces 2.2.
       -->
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"  
               prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
        -->

      </Host>
    </Engine>
  </Service>
</Server>

Bardzo proszę o ratunek :)

0

Jakiej wersji MySQL uzywasz? Jesli 5.x, zmien dialekt. Upewnij sie tez, ze Twoja baza jest dostepna (dziala i uzytkownik 'techfaq'@'localhost' ma odpowiednie uprawnienia).

0

Ogólnie to z baza nie raz udawało mi się łączyć przy pomocy zwykłego JDBC/Hibernate'a nie wykorzystującego tomcata. Zmiana dialektu nie przyniosła efektu. Wydaje mi się zatem, że to coś związanego z ustawieniami tomcata/aplikacji.

[adam@laptop ~]$ mysqladmin -u techfaq -p status
Enter password: 
Uptime: 9007  Threads: 1  Questions: 7  Slow queries: 0  Opens: 34  Flush tables: 1  Open tables: 27  Queries per second avg: 0.0
[adam@laptop ~]$ mysqladmin -u techfaq -p variables
[...]
| skip_networking                                   | OFF 
[...]
[[adam@laptop ~]$ telnet localhost 3306
Trying ::1...
Connection failed: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Connection closed by foreign host.
[adam@laptop ~]$ mysql -u techfaq -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.5.9-log Source distribution

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> show grants for 'techfaq'@'localhost';
+-------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for techfaq@localhost                                                                                                              |
+-------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'techfaq'@'localhost' IDENTIFIED BY PASSWORD '*1E40396B6FA8457472A52E254484AD83194F0F4E' WITH GRANT OPTION |
+-------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> quit
Bye
[adam@laptop ~]$ mysqladmin -u techfaq -p version
Enter password: 
mysqladmin  Ver 8.42 Distrib 5.5.9, for Linux on i686
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version		5.5.9-log
Protocol version	10
Connection		Localhost via UNIX socket
UNIX socket		/var/run/mysqld/mysqld.sock
Uptime:			2 hours 36 min 17 sec

Threads: 1  Questions: 11  Slow queries: 0  Opens: 34  Flush tables: 1  Open tables: 27  Queries per second avg: 0.1

1 użytkowników online, w tym zalogowanych: 0, gości: 1