users@glassfish.java.net

Re: Table in different schema with JPA

From: <glassfish_at_javadesktop.org>
Date: Tue, 23 Mar 2010 09:54:53 PDT

Well if you are using eclipselink as your Persistence Provider you can switch tables, schemas, and sequence @ID generators using the following as a sort of runtime dynamic JPA:

entitymanager= emf.createEntityManager();
session = ((JpaEntityManager)entitymanager.getDelegate()).getActiveSession();
                                
String tablename=session.getActiveSession().getClassDescriptor(YourBean.class).getTableName();
                                String schema=session.getActiveSession().getClassDescriptor(YourBean.class).getDefaultTable().getTableQualifier();
                                String column=session.getActiveSession().getClassDescriptor(YourBean.class).getMappingForAttributeName("somefield").getField().getName();
String sequence_name=session.getActiveSession().getClassDescriptor(YourBean.class).getSequence().getName();
so if you want to change the table or schema for a specific JPA entity to a new table/schema, do the following....

session.getActiveSession().getClassDescriptor(YourBean.class).getDefaultTable().setName("new_table_name");
                                        session.getActiveSession().getClassDescriptor(YourBean.class).getDefaultTable().setTableQualifier("schema_name");

Then do your normal JPA stuff...
entitymanager.getTransaction().begin();
                                Query query = entitymanager.createQuery("select e from Yourbean e");
                                List result = query.getResultList();


To add eclipselink, download the eclipselink jar, add it to your project and add <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> to your persistence.xml file.
[Message sent by forum member 'enderfake']

http://forums.java.net/jive/thread.jspa?messageID=393341