I'm in the process of migrating a Hibernate 4 application into a Hibernate 5 one. The application allows the possiblity of defining additional columns outside of the usual ones listed in an entity, which are modelled with a Map<String, Object> (call it additionalFields) in each entity (the key is the name of a field/column, while the value that field/column's value).
To model this so far we've had an entity (let's call it FieldDefinition) which contains the information of this mapping (the name of the field, the type, the precision or maximum length if that applies, etc.)
So, after creating the SessionFactory, we would use it to obtain a session, access all instances of FieldDefinition and add the mappings dynamically through configuration.getClassMapping(entityClassName), configuration.createMappings(), and related methods.
These last methods in Configuration have been removed from Hibernate 5, hence the problem I'm trying to solve. If I understand correctly, with the new API I would need to:
- Create a
SessionFactorythat understands aboutFieldDefinition. - Use it to access it and retrieve the
FieldDefinitions. - Having the instances of these entities, create a second
SessionFactory(becauseSessionFactoryis immutable, so I cannot modify the first one), where during the creation I use theMetadataSources.addFile()(or.addInputStream()) to addhbm.xmlfiles I need to create on the fly based on theFieldDefinitiondata to map the additional columns to theadditionalFieldsmaps (I couldn't find a programmatic way of adding mappings as was the case withconfiguration.createMappings()).
Alternatively, I can skip the first SessionFactory creation if I use the DataSource and JDBC directly, but the rest stays the same. I found this other SO question which points to more or less the same. Am I on the right track, or if not, what's the current recommended approach for such a case?
CodePudding user response:
You should be able to do this with a custom org.hibernate.boot.spi.MetadataContributor that is registered via a META-INF/services/org.hibernate.boot.spi.MetadataContributor file, since it is loaded through the java service loader mechanism.
There you have access to the PersistentClass where you can add you attributes, and at the same time you can make use of JdbcServics which you can use to query a table.
