views:

2121

answers:

6

(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)

+6  A: 

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
I'd like to stay within JPA if at all possible.
Thorbjørn Ravn Andersen
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
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
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
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
+2  A: 

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

dfa
+1  A: 

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.

Ambience
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
+4  A: 

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
very cool idea!
David Rabinowitz
A: 

I know this is an old thread but I have a question related to @Adam Paynter's possible solution.

Were you able to find a way to use this classloader. I'm using OpenJPA and this would be perfect for me. I'm trying to solve essentially the same problem.

@Thorbjørn Ravn Andersen, what solution did you finally settle on?

I've seen this pattern a few times now for SqlServer users who either don't understand partitioned tables and clustered indexes or don't want to pay for an enterprise license. I tried @Adam's solution and it worked very well. All I did was use the solution provided for custom classloading here http://openjpa.208410.n2.nabble.com/newbie-null-Entity-Manager-Factory-in-Eclipse-td3288915.html

The problem was that the classloader was never asked to load this class. It loaded everything else in the openJPA stack.

I'm still looking since Dynamic JPA requires that the table names be known at compile time for persistence.xml but I want to be able to add new tables into the future without recompiling the application. The application reads the table name from another database.

Any suggestions anyone?

Hugh
@Hugh, I never reached a satisfactory solution.
Thorbjørn Ravn Andersen
I managed to get a little further on this trail and got the classloader part to work. OpenJPA provides an Interface (ClassResolver) which is simple to implement and you just use the openjpa.ClassResolver property in the persistence.xml.Adams code ran as you'd expect, but the result was the same.
Hugh
It looks like TableAnnotationVisitor has no effect, even though it is run.
Hugh
A: 

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.

Damo