Get JTA DataSource properties - java

I would like to get my DataSource properties, like user name or url.
This is my persistence.xml:
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="defaulttransaction-type="JTA">
<jta-data-source>MyDataSource</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
</persistence-unit>
</persistence>
Inside GlassFish 4.1, I have the required JDBC Resource and JDBC ConnectionPool, respectively MyDataSource and MyDataSourceCP.
If this is useful, MyDataSource is a javax.sql.ConnectionPoolDataSource and MyDataSourceCP is a oracle.jdbc.pool.OracleConnectionPoolDataSource.
MyDataSourceCP is configured with some parameters like URL, user name and password.
I would like to extract those properties from Java.
So far, I have tried the following:
How to get jpa datasource properties from Entity Manager
How to retrieve the datasource used by a persistence unit programmatically
JPA - Is there a way/method to retrieve Persistence Unit information
But with no results.
As #Stoffelchen (in (1)), I would like something like
someObject.someMethod( ).getProperties( )
// or
someObject.someMethod( ).getProperties( "username" )
// or
someObject.someMethod( ).getUserName( )
Is there a way to achieve this?
I am using Hibernate 4.3.
Thanks in advance

Related

How do I use multiple databases with JPA?

I need two or more than two connections in my web application using jpa
To use different data sources, add multiple persistence units (say, source-1 and source-2 in persistence.xml and create multiple EntityManagerFactoryes by name):
EntityManagerFactory emf1 = Persistence.createEntityManagerFactory("source-1");
EntityManagerFactory emf2 = Persistence.createEntityManagerFactory("source-2");
or, if you're working on Spring or Java EE application server, inject them by name also:
#PersistenceUnit(name = "source-1")
EntityManagerFactory emf1;
#PersistenceContext(unitName = "source-2") // as an option
EntityManager em2;
persistence.xml will thus look like the following:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="source-1" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- source-1 properties here -->
</properties>
</persistence-unit>
<persistence-unit name="source-2" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- source-2 properties here -->
</properties>
</persistence-unit>
</persistence>
Example of how to configure persistence unit, create EntityManager to manage entities and execute queries can be found here.
For single datasource jpa will use multiple connections internally.So you don't need to do anything.

access denied when accessing mysql database through glassfish server

I'm following a tutorial which uses GlassFish to access a mysql database in NetBeans. The problem is I'm getting this error
Internal Exception: java.sql.SQLException: Error in allocating a
connection. Cause: Connection could not be allocated because: Access
denied for user 'root'#'localhost' (using password: NO)
when I try to deploy my app. I understand I need to add the password to the configuration so that GlassFish can establish the connection. The problem is I'm not sure where to include it within the persistence file.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="com.mycompany_MyApp_ejb_1.0-SNAPSHOTPU" transaction-type="JTA">
<jta-data-source>jdbc/creditpurchase</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
You can edit properties in glassfish admin console. Resources->JDBC->Connections Pools->your_connection_pool in Additional Properties tab. You can add property with name password. take a look here.
I was able to do it here:
C:\Code\Java\Glassfish\glassfish3\glassfish\domains\domain1\config\domain.xml
Change the properties within the jdbc-connection-pool tag

Hibernate tools: persistence unit not found

I have created a Hibernate / JPA project and I'd like to create entities from tables.
While the tool works like a charm selecting a pure Hibernate configuration, in the JPA mode it does not work, claiming the absence of the persistence unit
As shown in the following photo, the persistence unit is located in the folder /src/main/resources/META-INF
This is the code of persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="socialsports" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistenceProvider</provider>
<jta-data-source>jdbc/LiveDataSource</jta-data-source>
</persistence-unit>
</persistence>
This is the result of my attempt to run Hibernate tools to generate entities:
Since it only doesn't work in JPA mode, the use of the deprecated org.hibernate.ejb.HibernatePersistenceProvider could be a problem. Try org.hibernate.jpa.HibernatePersistenceProvider instead.

JPA MySQL Connection in Java EE project

I am running a local MySQL Server, later I want to use one on a remote computer and I have a question how to setup JPA in my Java EE project correctly.
First of all, do I have to setup the database connection in my application server or only in my persistence.xml? I have just added it in a JBoss Server and I can use JNDI now. But JNDI is not compatible with JPA, is it correct?
I tried it now with Geronimo and JBoss, with both I am not sure what I have to do correctly. I wanted to use OpenJPA as an JPA implementation which is standard on Geronimo.
I found many tutorials on the web, but most isnt very complet.
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="schulungen" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>MySQLServer</jta-data-source>
<class>model.Schulung</class>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema"/>
</properties>
</persistence-unit>
</persistence>
What is JTA-Data-Source? If I understood it right, it's a name given by the application server to identify the which connection I want.
Do I have to add properties like jdbc connection URL etc.?
I hope you understand my problem.

handle EntityManager dynamically with multiples persistences units

I have a database with multiples schemas so I have a persistence.xml file with multiples <persistence-unit /> (named 01, 02, ...).
Problematic :
I want to create an EntityManager dynamically function of some user criteria.
I have tested 2 cases.
First case : basically, I tested this code (inside stateless EJB) :
String criteria = "01";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(criteria);
EntityManager em = emf.createEntityManager();
Joueur joueur = new Joueur(); // Joueur is an Entity
joueur.setPseudo("olivier");
em.persist(joueur);
but I received exception :
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERREUR: la transaction est annulée, les commandes sont ignorées jusqu'à la fin du bloc
de la transaction
I thought, (with help of some Stackoverflow posts), that my EntityManager wasn't "linked" to my transaction context due to the fact it wasn't injected by container.
Second case : thus, I used injection :
#PersistenceContext(unitName="00")
private EntityManager em00;
#PersistenceContext(unitName="01")
private EntityManager em01;
Code in my function :
String criteria = "01";
EntityManager em = getEm(criteria);
...
and getEm() method :
private EntityManager getEm(String criteria){
if (criteria == "00")
return em00;
else if (criteria == "01")
return em01;
return null;
}
No problem, it's work but I have to inject as many EntityManagers that I have persistence-unit.
What will be the cost if I have 50 schemas...?
Is there a way to really manage entities managers dynamically ? (1 EntityManger only)
If I have to create 1 EntityManager per schema even if I don't use it, how can I improve my code to consume the least amount of resources possible ?
Thank you for advices and feedbacks
EDIT :
My configurations files :
Persistence.xml :
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="00" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/sim/00</jta-data-source>
<mapping-file>orm_00_beta.xml</mapping-file>
<class>com.sim.entities.Joueur</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
<persistence-unit name="01" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/sim/01</jta-data-source>
<mapping-file>orm_01_beta2.xml</mapping-file>
<class>com.sim.entities.Joueur</class>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
</persistence>
orm_00_beta.xml :
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema>beta</schema>
</persistence-unit-defaults>
</persistence-unit-metadata>
orm_01_beta2.xml :
<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0">
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema>beta2</schema>
</persistence-unit-defaults>
</persistence-unit-metadata>
You need to set the "eclipselink.target-server" to the application server you are using when using application managed persistence units (some servers set this automatically then using container managed persistence units). Then the EntityManager will bind with the JTA transaction that is active when it is created. If you create the EntityManager before the start of the JTA transaction then you can use joinTransaction().
If you still have issues, include the server you are using, and the full exception stack trace.
If you have a lot of schemas, you could consider using EclipseLink multi-tenant support, which allows each tenant to have their own schema.
http://www.eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_multitenant.htm#BABEGBIJ
Usually you don't have 50 schemas. I would not worry about the cost of injections, as usually EJB container has a pool of already opened connections which are ready to be injected. So the overhead is really small.
AFAIK, JPA does not allow dynamic entity managers.
If you care about resources, I would suggest to avoid using EclipseLink (I had really bad experience with EclipseLink + EJBs)
To optimize things a bit I would try to use factory pattern here. Create a Bean which will serve you EntityManagers. Instead of injecting several PersistenceContext you will have one injection with a method like:
EntityManager getEntityManager(String schemaId) {...}
Another option is to move all injections to an AbstractBean. All other beans inherit from the AbstractBean.

Categories