1

Not able to configure the hibernate getting context initialization exception, Have tried the alternate versions of Hibernate dependency, and although the table is created in DB, I think there is some issue related to Bean.

Student Entity

package com.spring.orm.Entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "student")
public class Student {

    @Id
    @Column(name = "student_id")
    private long studentId;
    @Column(name = "student_name")
    private String studentName;
    @Column(name = "student_city")
    private String studentCity;
    
    public long getStudentId() {
        return studentId;
    }
    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentCity() {
        return studentCity;
    }
    public void setStudentCity(String studentCity) {
        this.studentCity = studentCity;
    }
    public Student() {
    }
    public Student(long studentId, String studentName, String studentCity) {
        this.studentId = studentId;
        this.studentName = studentName;
        this.studentCity = studentCity;
    }

}

Student Dao

package com.spring.orm.Dao;

import com.spring.orm.Entity.Student;

public interface StudentDao {

    public Student insert(Student student);

}

Student Dao Impl

package com.spring.orm.Dao.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;

import com.spring.orm.Dao.StudentDao;
import com.spring.orm.Entity.Student;

public class StudentDaoImpl implements StudentDao{

    @Autowired
    private HibernateTemplate hibernateTemplate;
    
    @Override
    public Student insert(Student student) {
        Student st = (Student) hibernateTemplate.save(student);
        return st;
    }

}

Hibernate Configurations

package com.spring.orm.Config;

import java.io.IOException;
import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.spring.orm.Dao.Impl.StudentDaoImpl;
import com.spring.orm.Entity.Student;

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

    @Bean
    public Properties getHibernateProperties(){
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        System.out.println("Configured Hibernate properties");
        return properties;
    }
    
    @Bean
    public DriverManagerDataSource getDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
        dataSource.setUsername("root");
        dataSource.setPassword("qwsx##HG##123");
        System.out.println("Configured datasource");
        return dataSource;
    }
    
    @Bean
    public LocalSessionFactoryBean getSessionFactory(){
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(getDataSource());
        sessionFactory.setHibernateProperties(getHibernateProperties());
        sessionFactory.setPackagesToScan("com.spring.orm.Entity");
        System.out.println("Configured session factory");
        return sessionFactory;
    }
    
    @Bean(name = "hibernateTemplate")
    public HibernateTemplate getHibernateTemplate(){
        HibernateTemplate hibernateTemplateObj = new HibernateTemplate();
        hibernateTemplateObj.setSessionFactory(getSessionFactory().getObject());
        return hibernateTemplateObj;
    }
    
    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(getSessionFactory().getObject());
        return transactionManager;
    }
    
    @Bean(name = "studentImpl")
    public StudentDaoImpl getStudentDao(){
        StudentDaoImpl studentDaoImpl = new StudentDaoImpl();
        return studentDaoImpl;
    }

}

App.java

package com.spring.orm;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.spring.orm.Config.HibernateConfig;
import com.spring.orm.Dao.StudentDao;
import com.spring.orm.Entity.Student;

/\*\*

* Hello world!
* 

\*/
public class App
{
public static void main( String\[\] args )
{
System.out.println( "Application started!" );

        ApplicationContext context = new AnnotationConfigApplicationContext(HibernateConfig.class);
        StudentDao stDaoObj = context.getBean("studentImpl", StudentDao.class);
    
        Student st = new Student();
    
        st.setStudentId(44);
        st.setStudentName("Harshit Gupta");
        st.setStudentCity("Karera");
    
        stDaoObj.insert(st);
    }

}

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.spring.orm</groupId>
      <artifactId>springorm</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>springorm</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>6.1.3</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>6.1.3</version>
        </dependency>
    
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-orm</artifactId>
          <version>6.1.3</version>
        </dependency>
    
    
        <!-- https://mvnrepository.com/artifact/org.hibernate.orm/hibernate-core -->
    <dependency>
      <groupId>org.hibernate.orm</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>6.1.7.Final</version>
    </dependency>
    
        <dependency>
          <groupId>org.apache.tomcat</groupId>
          <artifactId>tomcat-dbcp</artifactId>
          <version>9.0.80</version>
      </dependency>
    
    
    
        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
        <dependency>
          <groupId>com.mysql</groupId>
          <artifactId>mysql-connector-j</artifactId>
          <version>8.3.0</version>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </project>

Exception

    Application started! Configured Hibernate properties Configured datasource Configured session factory Mar 10, 2024 9:04:26 AM org.hibernate.Version logVersion INFO: HHH000412: Hibernate ORM core version 6.1.5.Final Mar 10, 2024 9:04:27 AM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect Mar 10, 2024 9:04:27 AM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect WARN: HHH90000026: MySQL8Dialect has been deprecated; use org.hibernate.dialect.MySQLDialect instead Mar 10, 2024 9:04:27 AM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform] Mar 10, 2024 9:04:27 AM org.springframework.context.support.AbstractApplicationContext refresh WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in com.spring.orm.Config.HibernateConfig: Failed to instantiate [org.springframework.orm.hibernate5.HibernateTemplate]: Factory method 'getHibernateTemplate' threw exception with message: org/hibernate/criterion/Criterion Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in com.spring.orm.Config.HibernateConfig: Failed to instantiate [org.springframework.orm.hibernate5.HibernateTemplate]: Factory method 'getHibernateTemplate' threw exception with message: org/hibernate/criterion/Criterion        
         at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651)        
         at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:485)        
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334)        
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164)        
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:561)        
         at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521)        
         at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:325)        
         at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)        
         at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:323)        
         at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)        
         at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:975)        
         at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:959)        
         at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:624)        
         at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:93)        
         at com.spring.orm.App.main(App.java:20) 
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.hibernate5.HibernateTemplate]: 
    Factory method 'getHibernateTemplate' threw exception with message: org/hibernate/criterion/Criterion        
         at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:177)        
         at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:647)         
    ... 14 more Caused by: java.lang.NoClassDefFoundError: org/hibernate/criterion/Criterion        
         at com.spring.orm.Config.HibernateConfig.getHibernateTemplate(HibernateConfig.java:57)        
         at com.spring.orm.Config.HibernateConfig$$SpringCGLIB$$0.CGLIB$getHibernateTemplate$3(<generated>)        
         at com.spring.orm.Config.HibernateConfig$$SpringCGLIB$$FastClass$$1.invoke(<generated>)        
         at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:258)        
         at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331)        
         at com.spring.orm.Config.HibernateConfig$$SpringCGLIB$$0.getHibernateTemplate(<generated>)        
         at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)        
         at java.base/java.lang.reflect.Method.invoke(Method.java:580)        
         at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:140)      
    ... 15 more Caused by: java.lang.ClassNotFoundException: org.hibernate.criterion.Criterion        
         at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)        
         at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)        
         at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:526)         ... 24 more

Not able to configure hibernate template

2
  • java.lang.NoClassDefFoundError: org/hibernate/criterion/Criterion looks like a required jar is missing from the classpath. What dependency management tool are you using? Maven/Gradle? Please share pom or build.gradle files to understand the issue. Commented Mar 10, 2024 at 4:50
  • I'm using Maven sharing a pom as well. Commented Mar 10, 2024 at 5:21

2 Answers 2

0

Hibernate dropped Criteria-api before jakarta.annotations-api was introduced. Welcome to dependency hell!

Thats why the hibernate5 in

import org.springframework.orm.hibernate5.HibernateTemplate;

But your pom have hibernate version 6x.

Use this dependencies instead:

<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>2.7.18</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.6.15.Final</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-dbcp</artifactId>
        <version>9.0.80</version>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <version>8.3.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>

By the way: spring-data-jpa transitievly bind compatible spring-core, spring-orm and spring-context aswell.

Sign up to request clarification or add additional context in comments.

1 Comment

I don't know whether this will work or not because on simple googling I got to know In spring 5+ versions, HibernateTemplate was deprecated due to some performance issue instead we can directly inject the sessionFactory object in dao impl and can use sessionFactory.getCurrentSession() to perform CRUD operations.
0

After posting this question I was looking for an answer on different forums but on simple googling, I got to know that in the spring 5+ version, HibernateTemplate is deprecated instead we should inject the sessionFactory object directly in the 'Student Dao Impl' and it worked for me.

Updated hibernate Configurations

package com.spring.orm.Config;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.spring.orm.Dao.Impl.StudentDaoImpl;

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

    public Properties getHibernateProperties(){
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        properties.setProperty("hibernate.show_sql", "true");
        properties.setProperty("hibernate.hbm2ddl.auto", "update");
        System.out.println("Configured Hibernate properties");
        return properties;
    }

    @Bean
    public DriverManagerDataSource getDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
        dataSource.setUsername("root");
        dataSource.setPassword("qwsx##HG##123");
        System.out.println("Configured datasource");
        return dataSource;
    }
    
    @Bean
    public LocalSessionFactoryBean getSessionFactory(){
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(getDataSource());
        sessionFactory.setHibernateProperties(getHibernateProperties());
        sessionFactory.setPackagesToScan("com.spring.orm.Entity");
        System.out.println("Configured session factory");
        return sessionFactory;
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(getSessionFactory().getObject());
        return transactionManager;
    }

    @Bean(name = "studentImpl")
    public StudentDaoImpl getStudentDao(){
        StudentDaoImpl studentDaoImpl = new StudentDaoImpl();
        return studentDaoImpl;
    }
}

updated Student Dao Impl

package com.spring.orm.Dao.Impl;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import com.spring.orm.Dao.StudentDao;
import com.spring.orm.Entity.Student;


@Repository
@Transactional
@EnableTransactionManagement
public class StudentDaoImpl implements StudentDao{

    @Autowired
    private SessionFactory sessionFactory;


    @Override
    public void insert(Student student) {
        sessionFactory.getCurrentSession().persist(student);
    }


    @Override
    public void deleteStudentById(int id) {
        Student st = new Student();
        st.setStudentId(id);
        sessionFactory.getCurrentSession().remove(st);
    }


    // public void setSessionFactory(SessionFactory sessionFactory) {
    //     this.sessionFactory = sessionFactory;
    // }
    
}

Rest all the files are same

You can get more details here:-

Class HibernateTemplate

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.