MySQL JDBC Datasource lookup fails after updating to mysql-connector-java-5.1.44 - mysql

Consider following code snippet:
try
{//try to connect
conn = DatasourceProvider.getDatasource("java:comp/env/jdbc/mysql/my_db").getConnection();
}
catch(Exception ex)
{//failed to acquire connection from the pool, retry
ex.printStackTrace();
}
When I run it with mysql-connector-java-5.1.10-bin.jar loaded in tomcat 8.5 it works gracefully, but when I update to mysql-connector-java-5.1.44-bin.jar it throws following exception:
javax.naming.NameNotFoundException: Name [jdbc/mysql/my_db] is not bound in this Context. Unable to find [jdbc].
at org.apache.naming.NamingContext.lookup(NamingContext.java:816)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
at org.apache.naming.NamingContext.lookup(NamingContext.java:173)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
This happens on both MySQL5.6 and MySQL5.7.
Any Idea?

Related

Unable to commit against JDBC Connection

I am using springboot to connect to a mysql database. Please find my configuration below
spring.datasource.url=jdbc:<connection-url>
spring.datasource.username=<username>
spring.datasource.password=<password>
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
spring.datasource.tomcat.max-active=50
spring.datasource.tomcat.max-idle=20
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.min-idle=15
Api code
#CrossOrigin(origins = "*", allowedHeaders = "*")
#GetMapping(value = "/validateuser/{consumerName}")
#Transactional
public Boolean valiadateuser(#PathVariable String consumerName) {
LOGGER.info("Inside validateuser -1");
ConsumerName user = consumerRepository.findByName(consumerName);
LOGGER.info("Inside validateuser -2 :::: " + user);
if (user != null) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
Below is my exception
org.springframework.orm.jpa.JpaSystemException: Unable to commit against JDBC Connection; nested exception is org.hibernate.TransactionException: Unable to commit against JDBC Connection
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:353) ~[spring-orm-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255) ~[spring-orm-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:538) ~[spring-orm-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:665) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:370) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) [spring-tx-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) [spring-aop-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749) [spring-aop-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691) [spring-aop-5.2.5.RELEASE.jar!/:5.2.5.RELEASE]
at com.server.controller.SubscribeController$$EnhancerBySpringCGLIB$$14f090fd.subscribeTopic(<generated>) [classes!/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
Got the answer
updated the resource.properties
spring.datasource.url=jdbc:<connection-url>
spring.datasource.username=<username>
spring.datasource.password=<password>
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.datasource.hikari.connectionTimeout=20000
spring.datasource.hikari.maximumPoolSize=5
I was experiencing the same exception on my Spring / Postgres stack. Basically, the DB can not return/commit all the rows that match your query in time.
It can be fixed by creating indexes on the columns used in the particular query. This speeds the query up.
CREATE INDEX index_redflag_person
ON redflag_person (firstname, alias,lastname,address,birthplace);
I use Spring and Hibernate and PostgreSQL for practice, got the similar exception:
org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction;
nested exception is org.hibernate.TransactionException:
Unable to commit against JDBC Connection] with root cause
org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled.
my hibernate.prop has some config below
hibernate.dialect=org.hibernate.dialect.PostgreSQL10Dialect
hibernate.connection.handling_mode=DELAYED_ACQUISITION_AND_RELEASE_AFTER_STATEMENT
packages.to.scan=org.practice.dao.entity
It's weird bcs the default hibernate.connection.autocommit value in hibernate 5.6 is false
After a whole day search, I could not find the same error on the internet, finally I figured it out: somehow I added hibernate.connection.handling_mode in my config file, remove it(the default is fine) and the app works as expected
so maybe check the config and use the simplest param would help someone else

JDBC Connection error persists

I am using MySQL Workbench (5.6.19). It has several connections among which the table that i want to access is in "Connection1"(name of connection). Connection Host: 122.0.0.0 . My database name is "sorder". user = "root", password = "password",port = 3306.
Here's my piece of code:
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("Driver Connection Failed.");
e.printStackTrace();
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try
{
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sorder","root", "password");
} catch (SQLException e)
{
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
My driver connection failed. Plus i am not sure what my path Strin url should be since there are more than 1 connections in mySQL workbench.
error :
-------- MySQL JDBC Connection Testing ------------
Driver Connection Failed.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:126)
at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:63)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at org.apache.jsp.NewFile_jsp._jspService(NewFile_jsp.java:65)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
I followed whatever suggestions i got in different forums, like:
reassured that JAR file is there in build path.
reassured that JAR file is there in Window>Prefernces>Java>Build Path>Classpath variable
JAR file explicitily in WEB-INF/lib buildpath.
Thankful for any suggestions.
Regards.
when we manually created a xml file and added welcome-file-list, it worked. Default xml file was missing.

ESB Mule Client staring with xml-properties fails

I use Mule 3.x
I have a code that tests MuleClient connectivity.
This test is ok and works proper way:
public void testHello() throws Exception
{
MuleClient client = new MuleClient(muleContext);
MuleMessage result = client.send("http://127.0.0.1:8080/hello", "some data", null);
assertNotNull(result);
assertNull(result.getExceptionPayload());
assertFalse(result.getPayload() instanceof NullPayload);
//TODO Assert the correct data has been received
assertEquals("hello", result.getPayloadAsString());
}
But this tes is not ok - it fail with an connection exceptions:
public void testHello_with_Spring() throws Exception {
MuleClient client = new MuleClient("mule-config-test.xml");
client.getMuleContext().start();
//it fails here
MuleMessage result = client.send("http://127.0.0.1:8080/hello", "some data", null);
assertNotNull(result);
assertNull(result.getExceptionPayload());
assertFalse(result.getPayload() instanceof NullPayload);
//TODO Assert the correct data has been received
assertEquals("hello", result.getPayloadAsString());
}
The 'mule-config-test.xml' is used in both tests, the path for this file is ok, i checked.
This is error message I have in the end:
Exception stack is:
1. Address already in use (java.net.BindException) java.net.PlainSocketImpl:-2 (null)
2. Failed to bind to uri "http://127.0.0.1:8080/hello" (org.mule.transport.ConnectException)
org.mule.transport.tcp.TcpMessageReceiver:81
(http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/transport/ConnectException.html)
-------------------------------------------------------------------------------- Root Exception stack trace: java.net.BindException: Address already in
use at java.net.PlainSocketImpl.socketBind(Native Method) at
java.net.PlainSocketImpl.bind(PlainSocketImpl.java:383) at
java.net.ServerSocket.bind(ServerSocket.java:328)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
[10-05 16:33:37] ERROR HttpConnector [main]:
org.mule.transport.ConnectException: Failed to bind to uri
"http://127.0.0.1:8080/hello" [10-05 16:33:37] ERROR ConnectNotifier
[main]: Failed to connect/reconnect: HttpConnector {
name=connector.http.mule.default lifecycle=stop this=7578a7d9
numberOfConcurrentTransactedReceivers=4
createMultipleTransactedReceivers=true connected=false
supportedProtocols=[http] serviceOverrides= } . Root Exception
was: Address already in use. Type: class java.net.BindException [10-05
16:33:37] ERROR DefaultSystemExceptionStrategy [main]: Failed to bind
to uri "http://127.0.0.1:8080/hello"
org.mule.api.lifecycle.LifecycleException: Cannot process event as
"connector.http.mule.default" is stopped
I think the problem is in what you're not showing: testHello_with_Spring() is probably executing while Mule is already running. The second Mule you're starting in it then port-conflicts with the other one.
Are testHello() and testHello_with_Spring() in the same test suite? If yes, seeing that testHello() relies on an already running Mule, I'd say that would be the cause of port conflict for testHello_with_Spring().

connecting to MySQL using JDBC in eclipse

So I want to create a JDBC connection to MySQL server that is installed on my pc, here are the steps,
I installed MySQL with the username and password "root", downloaded mysql-connector-java and from theere I coped the JAR "mysql-connector-java-5.1.12-bin" to "C:\Sun\SDK\jdk\jre\lib\ext", I then added it as an external JAR in my project in eclipse, now in my class I have this code:
public void initialiseDatabase()
{
try {
// Load the Driver class.
Class.forName("com.mysql.jdbc.Driver");
//Create the connection using the static getConnection method
databaseConnection = DriverManager.getConnection (databaseUrl+databaseName,
dbUserName, dbPassword);
sqlStatement = databaseConnection.createStatement();
}
catch (SQLException e) {e.printStackTrace();}
catch (Exception e) {e.printStackTrace();}
}
(this is going to be psuedocode cause I am reading from a properties file and don't want the one helping me reading through long lines of code from main to figure out all the variables),
where databaseUrl = "127.0.0.1"
dbUserName = "root"
dbPassword = "root"
databaseName = "MySQL" //this one I am not sure of, do I need to create it or is it set inherenrly?
now the MySQL server is up and running, but when I call the method initialiseDatabase the following exception is thrown:
"java.sql.SQLException: No suitable driver found for rootroot
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Proxy$JDBCConnection.initialiseDatabase(Proxy.java:721)"
when line 721 is:
sqlStatement = databaseConnection.createStatement();
Where have I gone wrong?
thanks
Your database url should look like this:
jdbc:mysql://host:port/database
Example, if you use localhost, the default port and a database named cachedb, your url would be:
jdbc:mysql://localhost/cachedb

How to resolve this Exception : Data source rejected establishment of connection, message from server: "Too many connections"

I am using Hibernate 3 +Mysql 5.1 and after 98 insertion i am getting this Exception :
com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Data source rejected establishment of connection, message from server: "Too many connections"
My hibernate.cfg.xml file is :
com.mysql.jdbc.Driver
jdbc:mysql://localhost/xml
root
root
10
false
org.hibernate.dialect.MySQLDialect
update
true
Do you close your connections in a finally block?
something like this?
Session sess = factory.openSession();
Transaction tx;
try {
tx = sess.beginTransaction();
//do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
throw e;
}
finally {
sess.close();
}
If you don't you will be running out of connections.
I'd guess your application is leaking connections (opens them without properly closing them).