Reputation: 443
is it possible to access the information in <persistence-unit-metadata>
through Java API?
<persistence-unit-metadata>
<persistence-unit-defaults>
<schema>MySchema</schema>
</persistence-unit-defaults>
</persistence-unit-metadata>
I would like to read the schema "MySchema" via JPA API or EclipseLink API, which is the implementation I use.
Something like: entityManager.getDefaults().getSchema(); It's OK to cast or use any EclipseLink class, that's fine for this.
Thank you
Upvotes: 7
Views: 8347
Reputation: 1130
For database connections managed by Hibernate 6 the working solution I found was:
DataSource dataSource = (DataSource)entityManager
.getEntityManagerFactory()
.getProperties()
.get("hibernate.connection.datasource");
if (dataSource instanceof HikariDataSource hikariDataSource) {
final String url = hikariDataSource.getJdbcUrl();
// Parse the url according to your database engine ...
Upvotes: 0
Reputation: 161
I know is an old post, but worked for me with this
javax.persistence.Table table = MyEntity.class.getAnnotation(javax.persistence.Table.class)
from there you can get:
table.catalog()
table.indexes()
table.name()
table.schema()
table.uniqueConstraints()
Upvotes: 0
Reputation: 41
The previous replies didn't work for me. This is what I found to work:
String schema = em.unwrap(JpaEntityManager.class).getServerSession().getDescriptor(MyClass.class).getTables().get(0).getTableQualifier();
https://wiki.eclipse.org/EclipseLink/FAQ/JPA
Upvotes: 1
Reputation: 3701
I know this is an old question, but here is a simpler way to get the table name:
MyEntity.class.getAnnotation(javax.persistence.Entity.class).name();
Upvotes: 0
Reputation: 443
After debugging for a while I found a solution to access the schema of an entity.
EntityType<MyEntity> entity = emf.getMetamodel().entity(MyEntity.class);
EntityTypeImpl entityTypeImpl = (EntityTypeImpl) entity;
ClassDescriptor descriptor = entityTypeImpl.getDescriptor();
String schema = descriptor.getDefaultTable().getTableQualifier();
Looking for an easier and better way to access the information! Thank you so much.
Upvotes: 7