• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JPA - How to reconnect EntityManager

 
oscar montoya
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have source code

public class Main {
public static void main(String args[]) {

EntityManager em = Persistence.createEntityManagerFactory("JPA_EjemploPU").createEntityManager();


try {
System.out.println("Stop mysql");
Process p = Runtime.getRuntime().exec("net stop mysql");
Thread.sleep(5000);
System.out.println("Start mysql");
p = Runtime.getRuntime().exec("net start mysql");
Thread.sleep(5000);
} catch (Exception ex) {
ex.printStackTrace();
}





/* reconnect */
em = Persistence.createEntityManagerFactory("JPA_EjemploPU").createEntityManager();
Query q = em.createNamedQuery("AcClases.findAll");


List<AcClases> lista = q.getResultList();

for (AcClases acClases : lista) {
System.out.println(acClases.toString());
}
}
}

Throw the next excpetion

Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 10.516 milliseconds ago. The last packet sent successfully to the server was 0 milliseconds ago.
Error Code: 0
Call: SELECT CL_Id, CL_Clase FROM ac_clases


Can I resovle this problem... I need to reconnect connection.

Thanks.
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Oscar,

why not just keep a single reference to the EntityManagerFactory instead of trying to create multiple factories? Unfortunately I'm currently not sure if it is even allowed to create multiple instances for the same PU but if you have only one EntityManagerFactory it should be easy to create only a fresh EntityManager (in contrast to creating an EntityManager AND an EntityManagerFactory each time) when you need it.

Marco
 
James Sutherland
Ranch Hand
Posts: 553
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you close the EntityManagerFactory (all of them if multiple are open), then you will reconnect the next time you create a new factory.

Also you could get the TopLink ServerSession from the EntityManagerFactory and call logout() to login() on it to reconnect.

Also if you upgrade to EclipseLink from TopLink Essentials, then it will automatically reconnect dead connections.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic