无法配置Hibernate获取上下文初始化异常,我try 了Hibernate依赖的替代版本,虽然表是在DB中创建的,但我认为有一些与Bean相关的问题.

学生实体

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;
    }

}

学生刀

package com.spring.orm.Dao;

import com.spring.orm.Entity.Student;

public interface StudentDao {

    public Student insert(Student student);

}

学生刀 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 配置

package com.spring.orm.Config;

import java.io.IO展开;
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;
    }

}

♪应用程序.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/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>

展开

    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: 展开 encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreation展开: 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 展开 in thread "main" org.springframework.beans.factory.BeanCreation展开: 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(♪应用程序.Java♪:20) 
    Caused by: org.springframework.beans.BeanInstantiation展开: 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.ClassNotFound展开: 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

无法配置Hibernate 模板

推荐答案

在发布了这个问题后,我一直在不同的论坛上寻找答案,但通过简单的谷歌搜索,我知道在Spring5+版本中,HibernateTemplate是不推荐的,而我们应该直接将sessionFactory对象注入到‘Student Dao Impl’中,它对我起作用了.

更新的Hibernate 配置

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;
    }
}

更新的学生刀实施

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;
    // }
    
}

休息所有文件都是一样的

您可以在此处了解更多详细信息:-

Class HibernateTemplate

Java相关问答推荐

我们如何直接使用kerminldap服务票证来通过ldap进行身份验证并形成LDAP上下文

ittext pdf延迟签名,签名无效

如何配置ActiveMQ Artemis以使用AMQP 1.0和其他协议与Java

如何调整工作时间日历中的时间

安装Java Jar应用程序的Install4j遇到ClassNotFoundException的运行时错误

如何在Java中从XML中获取特定的 node ,然后将其删除?

Com.example.service.QuestionService中的构造函数的参数0需要找不到的类型为';com.example.Dao.QuestionDao;的Bean

Mac上的全屏截图在使用JavaFX时不能正常工作吗?

声明MessageChannel Bean的首选方式

带有可选部分的Java DateTimeForMatter

JavaFX:无论何时显示应用程序,如何更改组件/ node 位置?

在Spring Boot JPA for MySQL中为我的所有类创建Bean时出错?

具有多个模式的DateTimeForMatter的LocalDate.parse失败

如何调整JButton的大小以适应图标?

用于Java的Visual Studio代码完成不起作用

活泼的一次判断成语,结果中等

如何使用jOOQ在PostgreSQL中从枚举类型生成Java枚举

多线程、并发和睡眠未按预期工作

使用原子整数的共享计数器并发增量

Hibernate 命名策略导致 Java Spring Boot 应用程序中出现未知列错误