Unable to connect with MySql Database hosted on Amazon Web Server - mysql

Error Type
Type Exception Report
Message Request processing failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
I have created a simple Spring Mvc application that connects with the database, everything works well locally, ie localhost:8080
But when i hosted that in aws,i am not able to connect my application with the database.i created data bases and tables in mysql of aws.
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://34.201.126.236:3306/dbName?useSSL=false</property>
<property name="connection.username">root</property>
<property name="connection.password">secretPassword</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">10</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
What is the Problem?

Related

Unable to build Hibernate SessionFactory

in a jakarta - wildfly project when i try to run the project this error message appears.
Deploying on WildFly Application Server
profile mode: false
debug mode: false
force redeploy: true
Undeploying ...
Initial deploying EutopeanDynamics-shop-2022 to C:\Program Files\wildfly-27.0.1.Final\standalone\deployments\WebEshop.war
Completed initial distribution of EutopeanDynamics-shop-2022
Deploying C:\Program Files\wildfly-27.0.1.Final\standalone\deployments\WebEshop.war
"{\"WFLYCTL0080: Failed services\" => {\"jboss.persistenceunit.\\\"WebEshop.war#Persistence\\\"\" => \"jakarta.persistence.PersistenceException: [PersistenceUnit: Persistence] Unable to build Hibernate SessionFactory
Caused by: jakarta.persistence.PersistenceException: [PersistenceUnit: Persistence] Unable to build Hibernate SessionFactory
Caused by: org.hibernate.exception.GenericJDBCException: Unable to open JDBC Connection for DDL execution
Caused by: java.sql.SQLException: jakarta.resource.ResourceException: IJ000453: Unable to get managed connection for java:/MySqlDS
Caused by: jakarta.resource.ResourceException: IJ000453: Unable to get managed connection for java:/MySqlDS
Caused by: jakarta.resource.ResourceException: IJ031084: Unable to create connection
Caused by: java.sql.SQLException: Access denied for user 'admin'#'localhost' (using password: YES)\"}}"
Here is my persistence class
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="Persistence" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>java:/MySqlDS</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.globally_quoted_identifiers" value="true"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
I am using wildfly application server. The server is running and from localhost:9990 i created a datasource pointing in an empty database called 'eshop" as shown in the image above
enter image description here

Connecting Tomcat container to mysql container: JDBCConnectionException: Unable to acquire JDBC Connection

I'm trying to port my web-app created on Windows, using Hibernate, XAMPP for Apache tomcat and mysql server, to Linux, using Docker. I've deployed my war file under webapps folder on tomcat container, linked to mysql container ... the fact is that my web app is very very slow: i.e., the first feature is login/register form: on Linux, there is latency about minutes!
I've created containers with the following commands:
docker run -d --name mysql-phpmyadmin -p 127.0.0.1:8686:80 -p 127.0.0.1:3306:3306 grzesiekb/mysql-phpmyadmin
docker run -d -p 8484:8080 -p 8007:8009 --name tomcat8-linked --link mysql-phpmyadmin:mysqlphp tomcat:8.0-jre8
This is my hibernate.cfg.xml file:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- queste configurazioni sono per il testing in locale -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://mysqlphp:3306/at_db</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">mysql_pass</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">false</property>
<!--<property name="hibernate.hbm2ddl.auto">create-drop</property> se al posto di update metto create, mi cancella il db e lo rifa -->
<property name="hbm2ddl.auto">update</property>
<!-- Entity -->
<mapping class="com.ATBoscoCastellano.Entity.ClientUser" />
<mapping class="com.ATBoscoCastellano.Entity.GenericUser" />
<mapping class="com.ATBoscoCastellano.SessionManagement.SessionToken" />
<mapping class="com.ATBoscoCastellano.Entity.Post" />
<!-- <mapping class="it.boscus.StarFoods.entity.ExampleEmbeddableIDClass2" /> -->
</session-factory>
</hibernate-configuration>
And this is what I see from tomcat logs:
20-Feb-2017 07:48:15.869 SEVERE [http-apr-8080-exec-3] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [com.ATBoscoCastellano.servlets.UserSessionServlet] in context with path [/AtApplicazione1] threw exception
org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
....
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 232,149,705 milliseconds ago. The last packet sent successfully to the server was 232,149,705 milliseconds ago. is longer than the server configured
value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this probl
em.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:983)
at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3644)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2452)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2617)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2546)
at com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:4873)
at org.hibernate.engine.jdbc.connections.internal.PooledConnections.poll(PooledConnections.java:76)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:187)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:84)
... 34 more
Caused by: java.net.SocketException: Broken pipe (Write failed)
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
at java.net.SocketOutputStream.write(SocketOutputStream.java:155)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
I've tried adding autoReconnect=true on Url in hibernate, but still doesn't work. In my mysql my.cnf there is no wait_timeout line.
I have to tell that web-app works, but i attend a lot of time (tens of minutes) after my servlet (that interacts via hibernate with mysql container) works. This servlet, that manages login/register form, checks from the db the eventual presence of the inserted credentials.
I have tomcat container based on tomcat8.0-jre8 official docker image;
From mysql -V I have
root#1c53f40b63d3:/var/log/mysql# mysql -V
mysql Ver 14.14 Distrib 5.5.42, for debian-linux-gnu (x86_64) using readline 6.3
I really don't know why on Windows it works perfectly, but here not. My servlet remain in "pending" state ... i really want to know why there is so spending in time and how to solve it.

Connect a web-app on tomcat container to mysql container via hibernate

i'm trying to port my web-app from windows (using xampp for apache+mysql) to ubuntu (using docker container, so i have two containers: one with tomcat and another one with mysql.. they're linked).
Related to this question, i can't reach my sql container. It's creted from this image.
Tomcat container is created from official tomcat:8.0 image.
The two container are linked via a bridge docker network created.
It's a web-app that provides login+register service with checking user's presence in db.
I have to tell that on windows all works well.
This is my hibernate.cfg file:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- queste configurazioni sono per il testing in locale -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:49162/AT_DB</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">lxit</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">false</property>
<!--<property name="hibernate.hbm2ddl.auto">create-drop</property> se al posto di update metto create, mi cancella il db e lo rifa -->
<property name="hbm2ddl.auto">update</property>
<!-- Entity -->
<mapping class="com.ATBoscoCastellano.Entity.ClientUser" />
<mapping class="com.ATBoscoCastellano.Entity.GenericUser" />
<mapping class="com.ATBoscoCastellano.SessionManagement.SessionToken" />
<mapping class="com.ATBoscoCastellano.Entity.Post" />
<!-- <mapping class="it.boscus.StarFoods.entity.ExampleEmbeddableIDClass2" /> -->
</session-factory>
</hibernate-configuration>
After i insert my credential, i click on "login"; then there is a servlet named "UserSessionServlet" that checks if in the db is present an user with that credential; the error appairs when i click login, because UserSessionServlet return http 500 error.
[Edit] On tomcat container, i saw that logs tell me:
16-Feb-2017 09:43:41.498 SEVERE [http-nio-8080-exec-19] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [com.ATBoscoCastellano.servlets.UserSessionServlet] in context with path [/AtApplicazione1] threw exception [Servlet execution threw an
exception] with root cause
java.lang.NoClassDefFoundError: Could not initialize class com.ATBoscoCastellano.Util.HibernateUtil.HibernateUtil
at com.ATBoscoCastellano.Entity.GenericUser.checkIfUserExistsByEmail(GenericUser.java:198)
at com.ATBoscoCastellano.Entity.ClientUser.validateCredentials(ClientUser.java:259)
at com.ATBoscoCastellano.servlets.UserSessionServlet.doPost(UserSessionServlet.java:78)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:509)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
But all these classes exist, under opt/tomcat/webapps/AtApplicazione1/WEB-INF/classes/com/AtBoscoCastellano/some/paths.
I have to tell that i've not modified my tomcat container from official image (tomcat:8.0), so i can't know if it's configured for hibernate or not.
My war is structured as follows: three folders (META-INF, WEB-INF, template) and a file (.DS_Store). Because of my exception is :java.lang.NoClassDefFoundError: Could not initialize class com.ATBoscoCastellano.Util.HibernateUtil.HibernateUtil , in the war, this class is under WEB-INF/classes/com/ATBoscoCastellano/Util/HibernateUtil/ ... in which there is HibernateUtil .class and .java.
When i cmd java/javac -version on my tomcat container, its output is:
root#a26ff8018f3f:/opt/tomcat# java -version
java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)
root#a26ff8018f3f:/opt/tomcat# javac -version
javac "1.8.0_111"
[re-edit]: in my first requests, catalina logs says java.net.ConnectException: Connection refused; then, from the second request, it says to me always the same error.
[EDIT] now i'm using a new mysql container, named mysql-phpmyadmin from this image. I've linked tomcat container to this (new) container,; if i point, in the hibernate.cfg.xml, to localhost:PORT_MYSQL/AT_DB --> connection refused in tomcat log. If i point to mysql-phpmyadmin:PORT/AT_DB, tomcat logs says:
17-Feb-2017 08:31:25.649 SEVERE [http-apr-8080-exec-2] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [com.ATBoscoCastellano.servlets.UserSessionServlet] in context with path [/AtApplicazione1] threw exception [Servlet execution threw an e
xception] with root cause
java.sql.SQLException: null, message from server: "Host '172.17.0.9' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1038)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2254)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2285)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2084)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
I have to tell that, in config file within mysql container, there is bind_address 0.0.0.0
I think I have an idea why you are getting this exception. You are running 2 containers,
mysql container for data base
Tomcat container
Surely, your exception is due to static variable initialization exception,
public static final SessionFactory sessionFactory = buildSessionFactory();
Also, your property file has few problems,
connection.url should be hibernate.connection.url
You have mentioned your mysql hostname as localhost but it is running in another container. You should change it to "mysql" if you have named your mysql container as "mysql"
java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:214)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:298)
Clearly shows that your either
Mysql is not runnning. Check by making a connection from sql client like squirrel.
Tomcat container can't connect to mysql container. Check a quick ping by doing
docker exec tomcat ping mysql
Took me a while to deploy this application. I have solved the problem you have asked in this question. The primary problem was that mysql was not reachable from tomcat container. Also, the port specified was also not correct. Following is hibernate.cfg.xml,
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- queste configurazioni sono per il testing in locale -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://mysql:3306/AT_DB</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">lxit</property>
....rest of configuration....
</session-factory>
</hibernate-configuration>
There are few problems like following,
17-Feb-2017 16:07:53.156 INFO [http-nio-8080-exec-1] org.hibernate.dialect.Dialect.<init> HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
17-Feb-2017 16:07:53.776 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: ClientUser
17-Feb-2017 16:07:53.777 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: ClientUser
17-Feb-2017 16:07:53.818 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: Post
17-Feb-2017 16:07:53.819 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: Post
17-Feb-2017 16:07:53.828 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: SessionToken
17-Feb-2017 16:07:53.828 INFO [http-nio-8080-exec-1] org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults HHH000262: Table not found: SessionToken
17-Feb-2017 16:07:53.830 WARN [http-nio-8080-exec-1] org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl.handleException GenerationTarget encountered exception accepting command : Unable to execut
But these are due to case sensitivity of unix which was probably not there in case of Windows. Rest of the exception are trivial to solve. I ran following docker commands,
sudo docker run -ti --rm -p 8888:8080 -p 8009:8009 -v $(pwd):/usr/local/tomcat/webapps/ --name tomcat tomcat:9-jre8 bash
sudo docker run -d --name mysql -p 49162:3306 -p 49161:80 -p 49160:22 lxitgto/mysql-phpmyadmin:v1
and rest of the network command.

Cannot connect to the MySQL database using Spring Hibernate

I am completely new in Spring and fail to connect to my MySQL database by Spring Hibernate. I get
Request processing failed; nested exception is :
org.springframework.transaction.CannotCreateTransactionException:
Could not open JPA EntityManager for transaction; nested exception is
javax.persistence.PersistenceException:
org.hibernate.exception.GenericJDBCException: Could not open
connection
My applicationContext.xml
<context:annotation-config />
<context:component-scan base-package="Zoostore" />
<tx:annotation-driven />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/zoostore?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="your_password"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"
p:persistenceUnitName="BookJpaPersistenceUnit"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
And that is part of my controller code where I try to store data to database and get it from it
#RequestMapping(value = "saveadvert", method = RequestMethod.POST)
public ModelAndView saveAdvert(Advert advert) {
advert.setUserId(1);
advertService.persist(advert);
return new ModelAndView("test", "allAdverts", advertService.getAll());
This is the exception I get:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I can provide the root causes if necessary
Not sure which kind of error, I mention the conditions I had met.
make sure you open mysql service, you can test connect it with IDE database function, like IDEA.
take care of useSSL=false, sometimes it will be fatal.
If your mysql-connector-java's version is above 8.*, that you might need to change the datasource-driver-name to com.mysql.cj.jdbc.Driver
Though spring will help you change.
If you specify jpa with table's names, columns. Make sure you use the right grammar #Table(name='xxx') #Column(name= 'xxx')
Take care of the mysql server's port.
In windows. netstat -ano |findstr: 3306
taskkill /PIDĀ enterPIDĀ /F
In Linux netstat -anp |grep 3306 kill -9 pid
Check gradle or maven dependencies
And here is where I get stuck.
In spring-boot, you can make the configuration set up automatically. But you need to make the files right in their places.
xx.yml need put in resources(In IDEA, you need to specify the package as resources package)
xxxApplication.class(The spring-boot-starter class should be out of other classes, or you should specify the other classes' path.
First check your Sql client Version.
Goto Spring->ProjectName->WebContent->WEB-INF->lib and check you have the same mysql
connector jar version as of Sql Client.
Also change the same in Project->properties->Java-Build_path.
try this, it's works and solve your problem.
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"><context:annotation-config/><mvc:annotation-driven/><context:component-scan base-package="com.controller"/><bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"><property name="basename" value="/WEB-INF/Messages"/><property name="cacheSeconds" value="3000"/></bean><tx:annotation-driven transaction-manager="transactionManager"/><bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory"/><bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop><prop key="hibernate.show_sql">true</prop></props></property><property name="packagesToScan" value="com.controller"/></bean><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/demo1" p:username="root" p:password="chirag"/><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="maxUploadSize" value="10000000000"/></bean><bean id="viewResolver" class="org.springframework.web.servlet.view.Inter`enter code here`nalResourceViewResolver" p:prefix="/views/" p:suffix=".jsp"/></beans>

connection exception :CannotGetJdbcConnectionException: Could not load JDBC driver class ["com.microsoft.sqlserver.jdbc.SQLServerDriver";]

I have an web application in struts 1.3 which contain hibernate as ORM and spring as contextloaded AOP or as it is in general use.
I'm trying to deploy it in tomcat 6.0 server. earlier it was connected to mysql and it was working fine but now I want to connect it with MS Sql server 2008 so I downloaded "sqljdbc" and "sqljdbc4" jar and placed it into "C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\web1\WEB-INF\lib" location of my system. I have java 7 installed in my system.when I trying to run then its giving exception :
org.apache.jasper.JasperException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in ServletContext resource [/WEB-INF/applicationContext-hibernate.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyAccessExceptionsException: PropertyAccessExceptionsException (1 errors); nested propertyAccessExceptions are: [org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not load JDBC driver class ["com.microsoft.sqlserver.jdbc.SQLServerDriver";]; nested exception is java.lang.ClassNotFoundException: "com/microsoft/sqlserver/jdbc/SQLServerDriver";]
My jdbc property file entry is :
jdbc.driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
jdbc.url="jdbc:sqlserver://localhost:1433/databaseName=DB_1"
jdbc.username="dipak";
jdbc.password="";
hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect
ApplicationContext-Hibernate.xml
entry is :
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
Please help me to solve this problem, I Google a lot and tried many solutions but not get success yet, So any help would be much appreciated.
If you need any other/more information then please let me know.
Thanks,
-Dipak
Wrong spot for that JAR. Tomcat 6 and higher expects to find it in the Tomcat server /lib, not your application WEB-INF/lib. Move it and you'll see better results.
Make sure that your URL syntax is correct:
http://msdn.microsoft.com/en-us/library/ms378428(v=sql.90).aspx