Is there a way to do this with JPA 2.0?
I have multiple entities subclassing a MappedSuperclass. I can use dynamically generated orm.xml documents (as below) to assign database tables to my entities. However, these entities have ElementCollections and associated CollectionTables. How can I assign the collection table names?
The example below works fine if I name my collection tables "entitya_items" and "entityb_items". However, in my application I don't always know which entity (A or B -- they have different semantics) will be mapped to a given database table (and its corresponding collection table).
--Steve
Code:
@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Parent {
@Id
private Integer id;
@ElementCollection
private Set<String> items = new HashSet<String>();
}
public class EntityA extends Parent {
}
public class EntityB extends Parent {
}
public static void main(String[] args) {
Properties properties = new Properties();
properties.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
Ejb3Configuration ejb3Configuration = new Ejb3Configuration().configure("test", properties);
PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setDatabaseName(DB);
dataSource.setUser(USERNAME);
dataSource.setPassword(PASSWORD);
ejb3Configuration.setDataSource(dataSource);
String orm = getORM(
EntityA.class.getPackage().getName(),
EntityA.class.getSimpleName(),
"table_a");
ejb3Configuration.addInputStream(new ByteArrayInputStream(orm.getBytes()));
orm = getORM(
EntityB.class.getPackage().getName(),
EntityB.class.getSimpleName(),
"table_b");
ejb3Configuration.addInputStream(new ByteArrayInputStream(orm.getBytes()));
EntityManagerFactory emf = ejb3Configuration.buildEntityManagerFactory();
EntityManager em = emf.createEntityManager();
Object a = em.find(EntityA.class, Integer.valueOf(0));
System.out.println("Retrieved: " + a);
Object b = em.find(EntityB.class, Integer.valueOf(0));
System.out.println("Retrieved: " + b);
em.close();
emf.close();
}
private static final String EOL = "\n";
public static String getORM(String entityPackage, String entityName, String tableName) {
String s = new StringBuilder()
.append("<?xml version='1.0' encoding='UTF-8'?>" + EOL)
.append("<entity-mappings " + EOL)
.append(" xmlns='http://java.sun.com/xml/ns/persistence/orm' " + EOL)
.append(" xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + EOL)
.append(" xsi:schemaLocation='http://java.sun.com/xml/ns/persistence/orm " + EOL)
.append(" http://java.sun.com/xml/ns/persistence/orm_2_0.xsd'" + EOL)
.append(" version='2.0'>" + EOL)
.append(" <package>" + entityPackage + "</package>" + EOL)
.append(" <access>FIELD</access>" + EOL)
.append(" <entity class='" + entityName + "'>" + EOL)
.append(" <table name='" + tableName + "'/>" + EOL)
.append(" </entity>" + EOL)
.append("</entity-mappings>" + EOL)
.toString();
return s;
}