neo
neo

Reputation: 2471

JPA - Is there a way/method to retrieve Persistence Unit information

I'd like to find out my data source name in the code. Is there a way of doing that? I am using eclipselink.

thanks To be more specific, my aim is to get an jdbc connection object. I know i can do that thru:

datasource = (DataSource) (new InitialContext()).lookup("my_data_source_name")
connection = dataSource.getConnection();

But I don't want to hard code the data source name in my code.

I also tried

java.sql.Connection connection = em.unwrap(java.sql.Connection.class);

and it always return null.

Upvotes: 3

Views: 3644

Answers (3)

betatester07
betatester07

Reputation: 691

.unwrap() should be the way to go, as written in EclipseLink wiki.

I also used to get null when calling em.unwrap(java.sql.Connection.class); because it was not inside a transaction. When called like this:

em.getTransaction().begin();
java.sql.Connection conn = em.unwrap(java.sql.Connection.class);
// ...
em.getTransaction().commit();

everything works fine!

Upvotes: 7

James
James

Reputation: 18379

java.sql.Connection connection = em.unwrap(java.sql.Connection.class);

Should work, what version are you using? Ensure that a transaction is active.

To get the data source name you should be able to use,

((JNDIConnector)em.unwrap(JpaEntityManager.class).getSession().getLogin().getConnector()).getName();

Upvotes: 3

Kyle
Kyle

Reputation: 4238

Here's what I've found helpful:

private DataSource createDataSource() {
ClientDataSource dataSource = new ClientDataSource();
dataSource.setServerName("localhost");
dataSource.setPortNumber(1527);
dataSource.setDatabaseName("sample");
dataSource.setUser("app");
dataSource.setPassword("app");
return dataSource;
}

private EntityManagerFactory getEntityManagerFactory() {
if (emf == null) {
  Map properties = new HashMap();
  properties
     .put(PersistenceUnitProperties.NON_JTA_DATASOURCE,createDataSource());
  emf = Persistence.createEntityManagerFactory(PU_NAME, properties);
}
return emf;
}

Can you create your datasource in the code, rather than configure via persistence.xml?

Upvotes: 0

Related Questions