hibernate closing connections or not? - mysql

My code is below. Possibly I am using it many times in similar manner, i.e in simple words, I am managing the session and transaction this way:
List<Login> users= null;
try{
session=HibernateUtil.getSessionFactory().getCurrentSession();
tx=session.beginTransaction();
users=session.createQuery("from Login").list();
tx.commit();
}catch(Exception e){System.out.println("commit exception:"+e);
try {tx.rollback();} catch (Exception ex) {System.out.println("rollback exception:"+ex);}
}finally{if(session!=null && session.isOpen()){session.close();}}
return users;
Now, when I first run the database service(using MySQL) and check from command prompt using this query ...
show status like 'Conn%';
... the result is:
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Connections | 2 |
+---------------+-------+
When I start my application and use it. After opening few pages and querying the same thing. I am getting the connections as 6, I have even seen above 20.
Now I would like to know that hibernate is closing the connections or not?
I am handling all the transactions that way, I cross checked and dint see any code block without closing the session.
Hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/shareapp
</property>
<property name="connection.username">pluto</property>
<property name="connection.password">admin</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>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
</session-factory>
hibernateutil class
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Login.class);
config.addAnnotatedClass(FilesInfo.class);
config.addAnnotatedClass(FilesShare.class);
config.configure("hibernate.cfg.xml");
// new SchemaExport(config).create(true,true);
sessionFactory = config.buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Thanks!

The "Connections" status variable just refers to the
The number of connection attempts (successful or not) to the MySQL server,
and not the number of active connections.
Here is the link: http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html#statvar_Connections
To get the number of open connections, check the 'Threads_connected' variable, documented at
http://dev.mysql.com/doc/refman/5.1/en/server-status-variables.html#statvar_Threads_connected

Related

How to configure MySQL JTA resource in Spring, JPA and Hibernate for Glassfish v3?

My application is able to perform the read operations but unable to write to the database. How should I configure the JTA transaction manager? I'm using the following: Glassfish 3.1.2.2, Hibernate 4.2.21, Spring 4.2.5, MySQL 5.6 and JDK 1.6. I've tried the following configuration:
persistence.xml
<persistence-unit name="appPersistenceUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/app</jta-data-source>
<properties>
<!--<property name="hibernate.transaction.jta.platform"-->
<!--value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/>-->
<!--<property name="hibernate.transaction.factory_class" value="org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory"/>-->
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.connection.charSet" value="UTF-8"/>
</properties>
</persistence-unit>
web.xml
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/appPersistenceUnit</persistence-unit-ref-name>
<persistence-unit-name>appPersistenceUnit</persistence-unit-name>
</persistence-unit-ref>
applicationContext.xml
<jee:jndi-lookup id="entityManagerFactory"
jndi-name="persistence/appPersistenceUnit"/>
<tx:jta-transaction-manager/>
<tx:annotation-driven/>
MyDAOImpl.java
#PersistenceContext(type = PersistenceContextType.EXTENDED, name = "appPersistenceUnit")
protected EntityManager entityManager;
#Override
public int save(final MyEntity myEntity) {
try {
entityManager.merge(myEntity);
}
catch (Exception e) {
LOGGER.error("Error while saving MyEntity", e);
}
return 1; // id of the created element.
}
On trying to save the entity, I get the following error:
Cannot join transaction: do not override hibernate.transaction.factory_class
Please guide me. What am I doing wrong?

Rollback in MyBatis using JDBC (no Spring, no containers)

I've seen all sorts of posts on using Spring and MyBatis with transactions, but I'm facing a problem with rollbacks not working with plain old JDBC.
My ( test / throwaway) code is pretty simple : I open a session, insert a rec, throw an error on purpose and rollback the transaction. However, it always commits.
public static void main (String[] args){
//-- omitted for brevity
try {
org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sess = sqlSessionFactory.openSession(false);
BillsMapper mapper = sess.getMapper(BillsMapper.class);
BillState billState = new BillState();
billState.setBillId(-1);
billState.setLastName("TESTER");
billState.setFirstName("TESTER");
mapper.insert(billState);
logger.info("Post insert: key = {}", billState.getBillId());
if(1 == 1)
throw new RuntimeException("Error Thrown on purpose...testing rollback ");
sess.commit();
}catch(Exception e){
logger.error("Error: {}", e);
sess.rollback();
}finally{
sess.close();
logger.info("Finito!");
}
}
The logs show:
DEBUG | (BaseJdbcLogger.java:145) - ==> Preparing: insert into bills (users_userId, refId, firstName, ...
DEBUG | (BaseJdbcLogger.java:145) - ==> Parameters: 67(Integer), 67-120530180328(String), TESTER(String), ...
DEBUG | (BaseJdbcLogger.java:145) - <== Updates: 1
INFO | (TestAction.java:50) - Post insert: key = 2478
ERROR | (TestAction.java:56) - Error: {} java.lang.RuntimeException: Error Thrown on purpose...testing rollback at com.s2stest.TestAction.main(TestAction.java:53)
DEBUG | (JdbcTransaction.java:79) - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:122) - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (JdbcTransaction.java:90) - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection#371e88fb]
DEBUG | (PooledDataSource.java:344) - Returned connection 924748027 to pool.
Note the resetting of autocommit before closing the connection.... Would resetting autcommit before closing the SqlSession cause my rolled-back transaction to be committed? If so, is this a bug? Has anyone gotten JDBC working with transactions? I need it for testing, and I'd value some help. Right now, no transactions can be rolled back.
I've looked at the MyBatis source, and it indeed calls resetAutocommit before closing the connection. I'm using MySQL 5.6 and mysql-connector-java-5.1.36.jar for the driver if someone has a workaround that they've found.
--- UPDATE ---
mybatis-config.xml is as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="SLF4J" />
</settings>
<typeAliases>
<package name="com.ship2storage.domain" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mytestDb?zeroDateTimeBehavior=convertToNull" />
<property name="username" value="--shhh!!--" />
<property name="password" value="--shhh!!--" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ship2storage/db/maps/BillsMapper.xml" />
</mappers>
</configuration>
OK, I've found the answer by digging deeper into my setup. It seems that the MySQL storage engine I installed for my test DB is ISAM. ISAM does not support transactions. I switched to InnoDB using the following SQL tidbit, and transactions now work with JDBC:
ALTER TABLE bills ENGINE=InnoDB;
I haven't tried this, but it looks like you can also do this temporarily too:
SET default_storage_engine=InnoDB;
Hopefully this will help someone. The code/config posted above works.

WARN SqlExceptionHelper:143 - SQL Error: 0, SQLState: 08S01- SqlExceptionHelper:144 - Communications link failure

I have problem with Hibernate (hibernate-core-4.1.9.Final.jar)
Case 1: Hibernate testing inside for loop. Everything went well.
for(int i = 0; i < 1500; i++){
UserDAO.getInstance.getById(1);
}
Case 2: Thread.sleep() inside loop. Resulting with exception after 1 minute.
for(int i=0; i<1500; i++){
UserDAO.getInstance.getById(1);
Thread.sleep(60000);
}
Exception:
00:20:06,447 WARN SqlExceptionHelper:143 - SQL Error: 0, SQLState: 08S01
00:20:06,448 ERROR SqlExceptionHelper:144 - Communications link failure
The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago.
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Communications link failure
The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago.
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:131)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at sun.proxy.$Proxy11.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2031)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1832)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1811)
at org.hibernate.loader.Loader.doQuery(Loader.java:899)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2516)
at org.hibernate.loader.Loader.doList(Loader.java:2502)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2332)
at org.hibernate.loader.Loader.list(Loader.java:2327)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:124)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1621)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
at org.hibernate.internal.CriteriaImpl.uniqueResult(CriteriaImpl.java:396)
at com.fit.utilities.BaseDAO.getById(BaseDAO.java:35)
at com.fit.test.Testiranje.main(Testiranje.java:51)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 120,017 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3603)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3492)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4043)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 17 more
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3052)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3503)
... 29 more
Here is my hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://xxxxxx:3306/xxxx</property>
<property name="connection.username">xxxx</property>
<property name="connection.password">xxxx</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">false</property>
<property name="hibernate.connection.pool_size">1</property>
<mapping class="com.xxx.model.xxxxx" />
<mapping class="com.xxx.model.xxxxx" />
<mapping class="com.xxx.model.xxxxx" />
</session-factory>
</hibernate-configuration>
UPDATE:
The problem is solved using C3P0 library.
<!-- configuration pool via c3p0-->
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">100</property> <!-- seconds -->
The problem was happening because of the small value for time_out variable on the MySQL server.
In my situation, time_out was set to 1 minute.
Using C3PO pooling mechanism we can optimize JDBC.
Download c3p0 -> http://sourceforge.net/projects/c3p0/
I'm using hibernate 3.0.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://databasehost:3306/databasename</property>
<property name="connection.username">user</property>
<property name="connection.password">psw</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">false</property>
<!-- Hibernate c3p0 settings-->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquire_increment">3</property>
<property name="hibernate.c3p0.idle_test_period">10</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">75</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.timeout">50</property>
<property name="hibernate.c3p0.preferredTestQuery">select 1</property>
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
<!-- Mapping files -->
<mapping class="xxx.xxx.xxx.xxx" />
<mapping class="xxx.xxx.xxx.xxx" />
<mapping class="xxx.xxx.xxx.xxx" />
<mapping class="xxx.xxx.xxx.xxx" />
</session-factory>
</hibernate-configuration>
PersistenceManager.java
import java.io.PrintStream;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class PersistenceManager
{
private static SessionFactory sessionFactory = null;
private static PersistenceManager singleton = null;
public static PersistenceManager getInstance()
{
if (singleton == null)
{
singleton = new PersistenceManager();
}
return singleton;
}
public SessionFactory getSessionFactory()
{
if (sessionFactory == null)
createSessionFactory();
return sessionFactory;
}
protected void createSessionFactory()
{
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
}
public void destroySessionFactory()
{
if (sessionFactory != null)
{
sessionFactory.close();
sessionFactory = null;
}
}
}
Example 1:
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public Users Login( String username, String password)
{
Session session = null;
try
{
String hql = "select u from Users u where u.username like :p1 and u.password like :p2";
session = PersistenceManager.getInstance().getSessionFactory().openSession();
Query q = session.createQuery(hql)
.setParameter("p1", username)
.setParameter("p2", password);
if (q.list().size() == 0)
{
session.close();
return new Users();
}
Users user = (Users)q.list().get(0);
session.close();
return user;
}
catch (Exception e)
{
session.close();
}
}
Example 2:
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
public String Registration(Users u) {
Session session = null;
try
{
String hql = "select u from Users u where u.username like :p1";
session = PersistenceManager.getInstance().getSessionFactory().openSession();
Query q = session.createQuery(hql).setParameter("p1", u.getUsername());
if (q.list().size() == 0)
{
session.beginTransaction();
session.persist(u);
session.getTransaction().commit();
session.close();
return new Boolean(true).toString();
}
session.close();
return new Boolean(false).toString();
}
catch (Exception e)
{
return e.toString();
}
}
I had the same issue just because I forgot to wrap my hibernate code in a transaction.
Apparently the connection to DB is not closed until you commit a transaction.
Here is a valid example:
Session session = HibernateUtils.getSession();
Transaction tx = session.beginTransaction();
Category cat = null;
try{
cat = (Category)session.get(Category.class, 1);
tx.commit();
}catch(Exception ex){
tx.rollback();
}finally{
session.close();
}
return cat;

Having connection issue Hibernate 3.0 with MySQL

I am getting this error. I have my hibernate connections and MVC all setup correct I believe.
I heard MySQL drivers have an issue for database connection.
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/AdministrativeApplication] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection] with root cause
java.sql.SQLException: Unknown database 'testDB'
My hibernate configuration file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- Load Hibernate related configuration -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/testDB" />
<property name="username" value="myroot"/>
<property name="password" value="*****"/>
<!-- connection pooling details -->
<property name="initialSize" value="1"/>
<property name="maxActive" value="5"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<!-- Declare a transaction manager-->
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<!-- all the annotation entity classes -->
</list>
</property>
</bean>
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</beans>
Please let me know what
I could do to resolve this error.
I further added a new java file to test
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "******";
String url = "jdbc:mysql://localhost:3306/testDB";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace(System.out);
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
I get this error . Also I started the MySQL console with this command.
"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld.exe"
I get this error
java.sql.SQLException: Unknown database 'testdb'
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2975)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:798)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3700)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1203)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2572)
at com.mysql.jdbc.Connection.<init>(Connection.java:1485)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at Connect.main(Connect.java:15)
Cannot connect to database server
Can some please help resolve this.
i ran netstats no luck. I do not see at what port MySQL is listening at.
Thanks again .
Dhiren
I am getting this error.
This means you did something wrong.
I have my hibernate connections and MVC all setup correct I believe.
See my previous comment - you did not do everything correctly.
I heard MySQL drivers have an issue for database connection.
Nope - MySQL drivers work fine if you set them up properly. You're doing something wrong, and you'll make progress faster if you take that attitude.
Before you run Java, start up the MySQL client, log into MySQL. If you can't, Java won't be able to, either. See if the daemon is up and running.
See if you have that database available. If not, create it.
If it is created, make sure that you have the tables you need and the user you're logging in as has appropriate permissions.
You could create a database named "testDB" in your MySQL instance.

JPA + MySQL: After Timeout --> use a local Connection

as our connection is very unstable we have decided to switch to our local read-only database if a query times out.
But here is my problem: I do not get an exception when javax.persistence tries to query:
// Attribute
EntityManagerFactory entityManagerFactory;
EntityManager manager;
entityManagerFactory = Persistence
.createEntityManagerFactory("org.hibernate.tutorial.jpa");
manager = entityManagerFactory.createEntityManager();
try {
Query query = manager.createQuery(String.format(
"SELECT u FROM User u WHERE u.id = '%s'", 116));
User user = (User) query.getSingleResult();
manager.refresh(user);
System.out.println(user.getUsername());
} catch (org.hibernate.QueryTimeoutException ex) {
throw new QueryTimeoutException("timeout");
}
}
This is just a test to demonstrate my problem.
What am I missing?
Mysql: mysql-connector-java-5.1.16-bin.jar
JPA: javax.persistence_2.0.3.v201010191057.jar
Hibernate:
115 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
124 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.6.7.Final
126 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found
129 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
132 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
208 [main] INFO org.hibernate.ejb.Version - Hibernate EntityManager 3.6.7.Final
persistence.xml:
<properties>
<property name="hibernate.hbm2ddl.auto" value="valide"/>
<property name="hibernate.connection.url" value="jdbc:mysql:///database?zeroDateTimeBehavior=convertToNull"/>
<property name="hibernate.connection.username" value="user"/>
<property name="hibernate.connection.password" value="pass"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.query.timeout" value="1"/>
<property name="dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
Thank you
Tobias
Solution:
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://server/database", "user", "pass");
Every time I want to start a query I test if the Connection is alive:
if (connection.isValid(1)) {
return true;
} else {
throw new NoConnectionException();
You may not be seeing a timeout because some DBs don't support that feature.
"javax.persistence.query.timeout query timeout in milliseconds
(Integer or String), this is a hint used by Hibernate but requires
support by your underlying database."
See http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/configuration.html for more details.
I'd be inclined to switch to the read only all the time if you can't guarantee a reliable connection.