Object-relational Mapping Using JPA, Hibernate and Spring Data JPA. Switching between JP and Hibernate
It is possible that we are working with JPA and we need to access the Hibernate API. Or, vice-versa, we work with Hibernate native and we need to create an EntityManagerFactory from the Hibernate configuration.
To obtain a SessionFactory from an EntityManagerFactory, we’ll have to unwrap the first one from the second one.
Listing 7 Obtaining a SessionFactory from an EntityManagerFactory
private static SessionFactory getSessionFactory
(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.
unwrap(SessionFactory.class);
private static EntityManagerFactory
createEntityManagerFactory() {
Configuration configuration = new
Configuration(); #1
configuration.configure().
addAnnotatedClass(Item.class); #2
Map properties =
new HashMap<>(); #3
Enumeration propertyNames =
configuration.getProperties().
propertyNames(); #4
while (propertyNames.hasMoreElements()) {
String element = (String)
propertyNames.nextElement(); #5
properties.put(element,
configuration.getProperties().
getProperty(element)); #5
}
return Persistence.
createEntityManagerFactory("cscs",
properties); #6
}
- We create a new Hibernate configuration #1, then call the configure method, which adds the content of the default hibernate.cfg.xml file to the configuration.
- We explicitly add Item as annotated class #2.
- We create a new hash map to be filled in with the existing properties #3.
- We get all property names from Hibernate configuration #4, then we add them one by one to the previously created map #5.
- We return a new EntityManagerFactory, providing to it the cscs persistence unit name and the previously created map of properties #6.