MasamiSouji
MasamiSouji

Reputation: 1

Retrieve information from existing database using JPA

I'm developing a Java Web Project using JPA (EclipseLink) to connect with our databases. I have a persistence unit where I configured the database where my data is going to persisted. The question is that I also have to access another database that is already created and populated with info, and I just want to access one table of this database to retrieve some information. How can I access it using JPA just to retrieve info (neither save nor update anything).

Upvotes: 0

Views: 971

Answers (2)

Thiago
Thiago

Reputation: 997

So, you can create another persistent-unit poiting to your other database

<persistence-unit name="read-and-write-database">
        ...
    <properties>
        <!-- conection -->
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/database-write" />
        <.../>
    </properties>      
</persistence-unit>

<persistence-unit name="read-database">
        ...
    <properties>
        <!-- conection -->
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/database-read" />
        <.../>
    </properties>      
</persistence-unit>

And, in a SE environment, you would something like that to create the EntityManager:

EntityManagerFactory readWriteEntityManagerFactory = Persistence.createEntityManagerFactory("read-and-write-database");
EntityManager readWriteEntityManager = readWriteEntityManagerFactory.createEntityManager();

EntityManagerFactory readEntityManagerFactory = Persistence.createEntityManagerFactory("read-database");
EntityManager readEntityManager = readEntityManagerFactory.createEntityManager();

if you are in a container, the PersistenceContext anotation have the unitName field that you can use to define the persistente-unit

Keep in mind that by doing that, you will have two different persistence context. So, changes made in one of then, not gonna be "visiable" to the other one until the persistence of the data.

obs: sorry any typo.

I hope this helps you. Cheers

Upvotes: 1

Razvan
Razvan

Reputation: 367

After setting up your entity managers you can just run a native query :

entityManager.createNativeQuery("SELECT ...");

Upvotes: 1

Related Questions