Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the same database connection as JPA used using Java?

I am using Jasper Reports for report generation.

I am using temporary tables to generate reports for which I need the same connection used by JPA while creating temporary table how do I achieve the same.

like image 281
RPB Avatar asked Nov 02 '11 07:11

RPB


People also ask

How JPA will connect to database?

First, we need to obtain an instance of EntityManagerFactory that represents the relevant database and then we can use that factory instance to get an EntityManager instance. JPA requires the definition of a persistence unit in an XML file in order to be able to generate an EntityManagerFactory.

What is the type of bean associated with a database connection when using JPA?

You can use the Create EJB 3. x Session Bean wizard to create a session bean and a JPA entity in your EJB project.

What is the difference between JDBC and JPA?

JDBC is database-dependent, which means that different scripts must be written for different databases. On the other side, JPA is database-agnostic, meaning that the same code can be used in a variety of databases with few (or no) modifications.

What is a JPA EntityManagerFactory?

Several entity manager factories can be prepared for connecting to different data stores. JPA EntityManager is used to access a database in a particular application. It is used to manage persistent entity instances, to find entities by their primary key identity, and to query over all entities.


1 Answers

Probably you are just three steps away.

You can do it using following way

  1. use JTA datasource for persistance.xml like as below

    <persistence-unit name="sample">
            <jta-data-source>java:comp/env/jdbc/DBConnectionDS</jta-data-source>
            ....
    </persistence-unit>
    
  2. For report generation, retrieve the connection from datasource as shown below

    InitialContext initialContext = new InitialContext();
    DataSource dataSource = (DataSource)initialContext.lookup("java:comp/env/jdbc/DBConnectionDS");
    Connection connection = dataSource.getConnection();
    
  3. Use the connection to generate report something like below:

    JasperPrint print = JasperFillManager.fillReport(report, parameters, connection);
    

This should be all I believe. The idea is, using common JNDI connection for both, JPA & JasperReport, and then use them where applicable.

I didn't work with JasperReports, but worked with BIRT Report and solved it this way without any problem.

like image 50
Kowser Avatar answered Oct 19 '22 05:10

Kowser