Session Hibernate, how to obtain instance

Asked

Viewed 264 times

1

In all the Hibernate documentation, and web-based examples have this code example, or a very similar one, to use Hibernate.

List<Object> list = session.createCriteria(Object.class);

Since Session is an implementation of Hibernate’s Interface Session, but how do I get it, I’ve tried injecting it with @Autowired spring(Fremework MVC I’m using), but the java.lang.NullPointerException. The question is, how do I get the right instance of Ibernate. Session?

EDIT 1

What used to be done was like in the code snippet below:

Session session = (Session) this.entityManager.unwrap(Object.class);

or

Session session = this.entityManager.unwrap(Object.class);

But, it seems to me, this was taken from Hibernate 4.2 or 5.*, I don’t know for sure, what happens is that I’m not getting this instance of Ssion anymore, always gives null Pointer.

EDIT 2

I tried what @Javeson Yehudi suggested to me, which is the following :

private static final SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
session = sessionFactory.openSession();

However, it still doesn’t work, the eclipse itself didn’t let me use it, because the class AnnotationConfiguration(), not present in my libraries, but, as stated in the commentary, only Configuration() worked, only that changed the error, now he says that I do not have the xml Hibernate.cfg., because I am doing this configuration via code, with Spring... follows the error.

GRAVE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dashboardController': Unsatisfied dependency expressed through field 'iService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'infoService' defined in file [H:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Administrator\WEB-INF\classes\br\com\finger\service\InfoService.class]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4725)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1404)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1394)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'infoService' defined in file [H:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Administrator\WEB-INF\classes\br\com\finger\service\InfoService.class]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1110)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1055)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1056)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
    ... 24 more
Caused by: java.lang.ExceptionInInitializerError
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1103)
    ... 35 more
Caused by: org.hibernate.internal.util.config.ConfigurationException: Could not locate cfg.xml resource [hibernate.cfg.xml]
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:259)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:245)
    at br.com.finger.service.InfoService.<clinit>(InfoService.java:40)
    ... 42 more

"Solution"

After reading the Hibernate documentation, I realized that the approach was wrong, and that in fact, it is not possible to inject this Hibernate.Sessionfactory dependency anymore, it was deprecated to encourage the use of the JPA specification, which makes things easier to maintain later, although it adds a bit of complexity, but as a good practice it is better to opt for specifics. Follow the trex and the link that talks about it.

Hibernate offers an Older, legacy org.hibernate.Criteria API which should be considered deprecated. No Feature Development will target those Apis. Eventually, Hibernate-specific criteria Features will be Ported as Extensions to the JPA javax.persistence.criteria.CriteriaQuery. For Details on the org.hibernate.Criteria API, see Legacy Hibernate Criteria Queries.

https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#criteria

  • I wrote about this years ago, maybe the post will be useful to you: http://www.simpledev.com.br/spring-hibernate.html

  • Pretty cool your post... and exactly what I’m doing, only programmatically, because I don’t like xml

  • This post was written almost 4 years ago :)

  • Yes... that’s what I’m implementing now.

2 answers

1

If I’m understanding what you want, then you need Sessionfactory to get a Session

private static final SessionFactory sessionFactory =        new AnnotationConfiguration().configure().buildSessionFactory();
session = sessionFactory.openSession();

http://www.devmedia.com.br/entendendo-hibernate-session/29215

Now if you want with dependency injection, you can find cool things here

  • This class Annotationconfiguration(), came from where? I guess I don’t have this dependency in my libraries...

  • Depending on your version, try Configuration instead of Annotationconfiguration

  • I edited there... take a look at the error, please.

  • In fact, for you to use Configuration you need to have a Hibernate.cfg.xml is where it configures everything. As you are using Spring I think you have to use autowired, try to see this site http://www.baeldung.com/hibernate-4-spring

  • What actually happened @Javesonyehudi is that, according to the Hibernate documentation, Sessionfactory was set aside in version 5.2, to make the JPA specification, which is Entitymanager.getCriteriaBuilder()so I’m using the latest versions of spring and Hibernate, I can’t inject.

  • @Renatovieiradantas in fact I know that they are trying to give more attention to JPA. But they have not yet let go of Hibernate’s API. Could you give me an example of how you are setting up your configuration class? Why, if you want to use JPA’s Entitymanager the right thing to do is: @PersistenceContext(unitName = "myPersistenceUnit")&#xA;private EntityManager entityManager;&#xA; &#xA;ou&#xA; &#xA;@PersistenceUnit(unitName = "myPersistenceUnit")&#xA;private EntityManagerManager entityManagerManager; E for this you would have to have persistence.xml.

  • The configuration class is programmatic, spring allows us to make settings without xml... That’s exactly it, with @Persistencecontext itself, it was working perfectly like this, until I decided to change, but now I believe that the change will not be so great. And I will correct what I had said, in fact, they did not leave it aside, but it was considered deprecated.

  • Well, just to be clear: It is correct that Hibernate wants to give more attention to JPA, but the Session will not be deprecated (I had understood this). Now it will extend from Entitymanager. https://github.com/hibernate/hibernate-orm/wiki/Migration-Guide--5.2

  • Hmmmmmmm, so what’s going to happen and what are we going to keep using Session only by specification and not by implementation? That’s it?

Show 4 more comments

0

Instead of using the @Autowired try the @PersistenceContext.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.