3

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.

neo
  • 2,461
  • 9
  • 42
  • 67

3 Answers3

7

.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!

betatester07
  • 667
  • 8
  • 16
3
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();
James
  • 17,965
  • 11
  • 91
  • 146
0

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?

Kyle
  • 4,202
  • 1
  • 33
  • 41
  • thanks Kyle. I already created a persistence.xml. is there a method something like: getEntityManger().getDataSourceName() in JPA/Eclipselink api? – neo May 18 '11 at 14:51