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

对着背影说爱祢 提交于 2019-12-29 08:55:25

问题


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.


回答1:


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




回答2:


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();



回答3:


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?



来源:https://stackoverflow.com/questions/6046491/jpa-is-there-a-way-method-to-retrieve-persistence-unit-information

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!