14

(note: I'm quite familiar with Java, but not with Hibernate or JPA - yet :) )

I want to write an application which talks to a DB2/400 database through JPA and I have now that I can get all entries in the table and list them to System.out (used MyEclipse to reverse engineer). I understand that the @Table annotation results in the name being statically compiled with the class, but I need to be able to work with a table where the name and schema are provided at runtime (their defintion are the same, but we have many of them).

Apparently this is not SO easy to do, and I'd appreciate a hint.

I have currently chosen Hibernate as the JPA provider, as it can handle that these database tables are not journalled.

So, the question is, how can I at runtime tell the Hibernate implementation of JPA that class A corresponds to database table B?

(edit: an overridden tableName() in the Hibernate NamingStrategy may allow me to work around this intrinsic limitation, but I still would prefer a vendor agnostic JPA solution)

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347

5 Answers5

18

You need to use the XML version of the configuration rather than the annotations. That way you can dynamically generate the XML at runtime.

Or maybe something like Dynamic JPA would interest you?

I think it's necessary to further clarify the issues with this problem.

The first question is: are the set of tables where an entity can be stored known? By this I mean you aren't dynamically creating tables at runtime and wanting to associate entities with them. This scenario calls for, say, three tables to be known at compile-time. If that is the case you can possibly use JPA inheritance. The OpenJPA documentation details the table per class inheritance strategy.

The advantage of this method is that it is pure JPA. It comes with limitations however, being that the tables have to be known and you can't easily change which table a given object is stored in (if that's a requirement for you), just like objects in OO systems don't generally change class or type.

If you want this to be truly dynamic and to move entities between tables (essentially) then I'm not sure JPA is the right tool for you. An awful lot of magic goes into making JPA work including load-time weaving (instrumentation) and usually one or more levels of caching. What's more the entity manager needs to record changes and handle updates of managed objects. There is no easy facility that I know of to instruct the entity manager that a given entity should be stored in one table or another.

Such a move operation would implicitly require a delete from one table and insertion into another. If there are child entities this gets more difficult. Not impossible mind you but it's such an unusual corner case I'm not sure anyone would ever bother.

A lower-level SQL/JDBC framework such as Ibatis may be a better bet as it will give you the control that you want.

I've also given thought to dynamically changing or assigning at annotations at runtime. While I'm not yet sure if that's even possible, even if it is I'm not sure it'd necessarily help. I can't imagine an entity manager or the caching not getting hopelessly confused by that kind of thing happening.

The other possibility I thought of was dynamically creating subclasses at runtime (as anonymous subclasses) but that still has the annotation problem and again I'm not sure how you add that to an existing persistence unit.

It might help if you provided some more detail on what you're doing and why. Whatever it is though, I'm leaning towards thinking you need to rethink what you're doing or how you're doing it or you need to pick a different persistence technology.

cletus
  • 616,129
  • 168
  • 910
  • 942
  • I'd like to stay within JPA if at all possible. – Thorbjørn Ravn Andersen May 25 '09 at 13:33
  • Question 1: The table schema is fixed, but the table names are not. This means that if A, B, and C were to be edited, they would all share the same schema and be logically separate identities. I.e. items will not be moved from A to B or similar. I _could_ in principle get along with reading in pages in a map per row and work with that, but I am trying to get the "hey, somebody else updated this row" functionality. – Thorbjørn Ravn Andersen Jun 04 '09 at 23:05
  • I will ponder a bit on how to solve this the best based on the feedback, and it may be that this is technologically overkill. I also have to consider that this will probably be used for a long time so it should not be unneccesarily complex for future maintainers. – Thorbjørn Ravn Andersen Jun 04 '09 at 23:08
  • The issue with the table names changing is important. If you think about it: how does JPA know to get a particular entity from a particular table? How does it know to persist changes there? You would have to somehow dynamically "enrol" a new dynamically-created entity into the persistence unit. – cletus Jun 04 '09 at 23:28
  • That all being said, perhaps the Dynamic JPA + OSGi route could be beneficial to you so you could redeploy your entity structure at runtime with entities for new tables and so on. Still, it's not exactly what it was designed for. – cletus Jun 04 '09 at 23:30
10

You may be able to specify the table name at load time via a custom ClassLoader that re-writes the @Table annotation on classes as they are loaded. At the moment, I am not 100% sure how you would ensure Hibernate is loading its classes via this ClassLoader.

Classes are re-written using the ASM bytecode framework.

Warning: These classes are experimental.

public class TableClassLoader extends ClassLoader {

    private final Map<String, String> tablesByClassName;

    public TableClassLoader(Map<String, String> tablesByClassName) {
        super();
        this.tablesByClassName = tablesByClassName;
    }

    public TableClassLoader(Map<String, String> tablesByClassName, ClassLoader parent) {
        super(parent);
        this.tablesByClassName = tablesByClassName;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        if (tablesByClassName.containsKey(name)) {
            String table = tablesByClassName.get(name);
            return loadCustomizedClass(name, table);
        } else {
            return super.loadClass(name);
        }
    }

    public Class<?> loadCustomizedClass(String className, String table) throws ClassNotFoundException {
        try {
            String resourceName = getResourceName(className);
            InputStream inputStream = super.getResourceAsStream(resourceName);
            ClassReader classReader = new ClassReader(inputStream);
            ClassWriter classWriter = new ClassWriter(0);
            classReader.accept(new TableClassVisitor(classWriter, table), 0);

            byte[] classByteArray = classWriter.toByteArray();

            return super.defineClass(className, classByteArray, 0, classByteArray.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private String getResourceName(String className) {
        Type type = Type.getObjectType(className);
        String internalName = type.getInternalName();
        return internalName.replaceAll("\\.", "/") + ".class";
    }

}

The TableClassLoader relies on the TableClassVisitor to catch the visitAnnotation method calls:

public class TableClassVisitor extends ClassAdapter {

    private static final String tableDesc = Type.getDescriptor(Table.class);

    private final String table;

    public TableClassVisitor(ClassVisitor visitor, String table) {
        super(visitor);
        this.table = table;
    }

    @Override
    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
        AnnotationVisitor annotationVisitor;

        if (desc.equals(tableDesc)) {
            annotationVisitor = new TableAnnotationVisitor(super.visitAnnotation(desc, visible), table);
        } else {
            annotationVisitor = super.visitAnnotation(desc, visible);
        }

        return annotationVisitor;
    }

}

The TableAnnotationVisitor is ultimately responsible for changing the name field of the @Table annotation:

public class TableAnnotationVisitor extends AnnotationAdapter {

    public final String table;

    public TableAnnotationVisitor(AnnotationVisitor visitor, String table) {
        super(visitor);
        this.table = table;
    }

    @Override
    public void visit(String name, Object value) {
        if (name.equals("name")) {
            super.visit(name, table);
        } else {
            super.visit(name, value);
        }
    }

}

Because I didn't happen to find an AnnotationAdapter class in ASM's library, here is one I made myself:

public class AnnotationAdapter implements AnnotationVisitor {

    private final AnnotationVisitor visitor;

    public AnnotationAdapter(AnnotationVisitor visitor) {
        this.visitor = visitor;
    }

    @Override
    public void visit(String name, Object value) {
        visitor.visit(name, value);
    }

    @Override
    public AnnotationVisitor visitAnnotation(String name, String desc) {
        return visitor.visitAnnotation(name, desc);
    }

    @Override
    public AnnotationVisitor visitArray(String name) {
        return visitor.visitArray(name);
    }

    @Override
    public void visitEnd() {
        visitor.visitEnd();
    }

    @Override
    public void visitEnum(String name, String desc, String value) {
        visitor.visitEnum(name, desc, value);
    }

}
Adam Paynter
  • 46,244
  • 33
  • 149
  • 164
  • 2
    Excellent, Works with a tiny amount of massaging, using it to manage DynamoDBTable annotation. Now to see if my web container allows the custom class loader. – stjohnroe Feb 07 '12 at 15:16
5

It sounds to me like what you're after is Overriding the JPA Annotations with an ORM.xml.

This will allow you to specify the Annotations but then override them only where they change. I've done the same to override the schema in the @Table annotation as it changes between my environments.

Using this approach you can also override the table name on individual entities.

[Updating this answer as it's not well documented and someone else may find it useful]

Here's my orm.xml file (note that I am only overriding the schema and leaving the other JPA & Hibernate annotations alone, however changing the table here is totally possible. Also note that I am annotating on the field not the Getter)

<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings 
  xmlns="http://java.sun.com/xml/ns/persistence/orm"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
  version="1.0">
    <package>models.jpa.eglobal</package>
    <entity class="MyEntityOne" access="FIELD">
        <table name="ENTITY_ONE" schema="MY_SCHEMA"/>
    </entity> 
    <entity class="MyEntityTwo" access="FIELD">
        <table name="ENTITY_TWO" schema="MY_SCHEMA"/>
    </entity> 
</entity-mappings>
Damo
  • 11,410
  • 5
  • 57
  • 74
  • perfect this solved the problem for me. **BTW:** you have to but orm.xml in META-INF under your classpath – Jeremy S. Feb 15 '12 at 15:38
3

as alternative of XML configuration, you may want to dynamically generate java class with annotation using your preferred bytecode manipulation framework

dfa
  • 114,442
  • 31
  • 189
  • 228
1

If you don't mind binding your self to Hibernate, you could use some of the methods described at https://www.hibernate.org/171.html . You may find your self using quite a few hibernate annotations depending on the complexity of your data, as they go above and beyond the JPA spec, so it may be a small price to pay.

Steve Skrla
  • 1,620
  • 5
  • 16
  • 24
  • I would prefer JPA, but Hibernate is also an option. As mentioned the schema is static but I will need to edit one or more database tables in a single session only differing by table name. – Thorbjørn Ravn Andersen Jun 04 '09 at 22:59