How to get the current session in sleep mode

I am trying to get the current hibernation session to create a Query criterion, but I am getting an error.

Here is my code:

datasource.xml:

    <bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceUnitName" ref="persistenceUnit" />
    <property name="jpaProperties" ref="jpaProperties" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <property name="dataSource" ref="dataSource" />
    <property name="globalRollbackOnParticipationFailure" value="true" />
</bean>

<bean id="jpaVendorAdapter"
    class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="databasePlatform" ref="sqlDialect" />
</bean>

      

java class:

    @Autowired
    private SessionFactory  sessionFactory;
    Session session = sessionFactory.getCurrentSession();

    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
    List<Product> bookResult = new ArrayList<>();
    try {
        // This will ensure that index for already inserted data is created.
        fullTextEntityManager.createIndexer().startAndWait();
        QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Product.class).get();
    org.apache.lucene.search.Query query = qb.keyword().onFields("name").matching("cocacola").createQuery();
        javax.persistence.Query jpaQuery = fullTextEntityManager.createFullTextQuery(query, Product.class);

        Criteria criteria = session.createCriteria(Product.class);
        criteria.add(Restrictions.eq("category.supermarket", "mercadona"));

        List<Product> productos = criteria.list();

      

But get this error:

org.hibernate.HibernateException: Session not found for current theme in org.springframework.orm.hibernate4.SpringSessionContext.currentSession (SpringSessionContext.java:106)

How can I solve this?

+3


source to share


1 answer


Are you adding your servlet context .xml

<tx:annotation-driven transaction-manager="transactionManager" />

      



use @Transaction?

And also check if @Autowired is correct, for example System.out.println(sessionFactory)

in your .java class which is not null.

0


source







All Articles