Typesafe Entity References for Hibernate/JPA
It would seem Gavin King's having similar thoughts to something I was working on last week, only with a much larger and grander scale:
The first problem isn't really solvable without major new language features (usually described as "DSL support"). The second problem could easily be solved by adding a typesafe literal syntax for methods and fields to Java. This is now a sorely needed feature of the language, it's especially useful in combination with annotations.
...
The metamodel API is a bit like the Java reflection API, except that it is provided by the JPA persistence provider, is aware of the JPA metadata, and uses generics in a clever way. (Also it uses unchecked exceptions.) For example, to obtain an object that represents an entity, we call the MetaModel object:
import javax.jpa.metamodel.Entity; ... Entityorder = metaModel.entity(Order.class); Entity - item = metaModel.entity(Item.class); Entity
item = metaModel.entity(Product.class); ...
Last week I was working on some code that was suffering from an over abundance of eagerly loaded collections - both performance and problems with passing instances between transactions were causing no end of headaches. In the end, the solution I came up with was to rework the front end queries to only return ids, and wrap them in light weight, type-safe reference:
... Referenceperson = Reference.referenceTo(Person.class, 32); Reference anotherPerson = Reference.referenceTo(someExistingPerson); ...
As the Reference holds only the id and class, they're very easily to throw around between threads, sessions and transactions, resolving the reference is a simple call to Reference#load(Session) relative to a session or entity manager.
... Person fullPerson = person.load(sessionFactory.getCurrentSession()); ...
Whilst the usage requirements and usage differ vastly between my small solution, they both add much needed functionality to Hibernate.