Lucio Crusca
Lucio Crusca

Reputation: 1507

JPA: finding class from table name

I have a `documents` table

CREATE TABLE `documents` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`docnum` int(11) default null,
`docdate` DATE default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 

and corresponding Documents @Entity. Then I have a orders, invoices and other similar tables that have 1-to-1 relationship with documents. Documents entity declares joined inheritance and derived Orders, Invoices,... entities use @PrimaryKeyJoinColumn. Everything works as expected.

Then I have a table that establishes some weak relationship between various documents types:

CREATE TABLE IF NOT EXISTS `documents_xref` (
  `id` int(11) not null auto_increment primary key,
  `xrefdate` DATE not null,
  `src_doc` int(11) not null,
  `src_doc_tablename` VARCHAR(250) not null,
  `dst_doc` int(11) not null unique,
  `dst_doc_tablename` VARCHAR(250) not null,
  INDEX(`src_doc`),
  CONSTRAINT FOREIGN KEY (`src_doc`) REFERENCES `documents` (`id`),
  CONSTRAINT FOREIGN KEY (`dst_doc`) REFERENCES `documents` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ;

Now I need to display a graph of relationships between documents, and each node of the graph must tell what type of document it is, so that I need to find the @Entity class from the table name. Is there a way other than brute force to obtain it from JPA2?

On a side note: could anyone with 1500 rep create the "joined-inheritance" tag for me if he feels like doing so and attach it to my question? Thanks a lot.

Upvotes: 0

Views: 47

Answers (1)

James
James

Reputation: 18379

This would be provider specific, as you would need to access the internal JPA meta-data, unless you process all of the annotations/xml yourself, or define your own hard coded map between tables and classes.

For EclipseLink you can unwrap the EclipseLink Session from the EntityManagerFactory and access all of the descriptors.

for (ClassDescriptor descriptor : emf.unwrap(Session.class).getDescriptors().values()) {
  Class entityClass = descriptor.getJavaClass();
  List<String> tables = descriptors.getTableNames();
}

Upvotes: 1

Related Questions