java - 需要找不到类型为 'org.hibernate.SessionFactory' 的 bean

标签 java spring hibernate maven spring-boot

每当启动应用程序 spring boot 时,我都会收到以下错误。


应用程序启动失败


描述:

com.base.model.AbstractDao 中的字段 session 需要一个类型为“org.hibernate.SessionFactory”的 bean,但找不到。

行动:

考虑在您的配置中定义类型为“org.hibernate.SessionFactory”的 bean。

我已经添加了我的应用程序的实现:

POM.xml

    <?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>


    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Hibernate dependency -->

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.1.5.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.3.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

应用程序属性

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username = root
spring.datasource.password = root
hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

配置类

@Configuration
@EnableTransactionManagement
@ComponentScan({"configure"})
@PropertySource({"classpath:application.properties"})
public class HibernateConfiguration {

    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactory(){
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[]{"com.base","com.base.model"});
        sessionFactory.setMappingResources(new String[]{"Employee.hbm.xml"});
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Bean
    public Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hiberante.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        return properties;
    }

    @Bean
    public DataSource dataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
            dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
            dataSource.setUsername(environment.getRequiredProperty("jdbc.userName"));
            dataSource.setUsername(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean  
    public SessionFactory sessionFactory(HibernateEntityManagerFactory hemf){  
        return hemf.getSessionFactory();  
    }  

}

员工.java

public class Employee implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private int id;

    private String name;

    private String country;

    public int getId(){
        return this.id;
    }

    public void setId(int id){
        this.id = id;
    }

    public String getName(){
        return this.name;
    }

    public void setName(String name){
        this.name = name;
    }

    public void setCountry(String country){
        this.country = country;
    }

    public String getCountry(){
        return this.getCountry();
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", country="
                + country + "]";
    }
}

员工.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.base.model.Employee" table="Person">
        <id name="id" type="java.lang.Integer">
            <generator class="native"></generator>
        </id>

        <property name="name" type="java.lang.String">
            <column name="name" not-null="true"></column>
        </property>
        <property name="country" type="java.lang.String">
            <column name="country"></column>
        </property>
    </class>

</hibernate-mapping>

EmployeeDaoImpl

@Component
public class EmployeeDataDaoImpl  {


    @Autowired
    SessionFactory sessionFactory;


public List<Employee> findAllEmployee(){
////    Criteria cri = getSession().createCriteria(Employee.class);
//  List<Employee> dbList = cri.list();
//  for (Employee employee : dbList) {
//      System.out.println(employee.getCountry());
//  }
    return null;
}

}

我在 stackoverflow 上查找了相同的错误代码,但没有一个解决方案有效,因此将其与我的代码一起再次发布在这里。 希望其他人可以指出我哪里出错了。

最佳答案

对于初学者来说,您的配置有几件事

  1. 混合来自不同 Spring 和 Hibernate 版本的 jar
  2. 也可能已经管理依赖项
  3. 努力变得比 Spring Boot 更聪明。

对于 1. 和 2. 只需删除 <version> spring-orm 的标签和 hibernate-corehibernate-entitymanager管理器依赖项。 Spring Boot 已经在管理这些。您实际上可以删除所有 org.springframework那些已经被初学者引入的依赖项(实际上还有 hibernate 的依赖项)。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

接下来在您的配置中您至少有 2 个 SessionFactory的配置。我建议使用注释来定义您的实体而不是 hbm.xml文件。

@Entity
@Table("person")
public class Employee implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private int id;

    @Column(nullable=false)
    private String name;

    private String country;

}

当使用 JPA 注释时,Hibernate 将自动检测您的实体(特别是与 Spring Boot 结合使用),这使得它非常强大。当然你现在可以删除你的 Employee.hbm.xml .

下一个你的EmployeeDataDaoImpl我强烈建议使用普通的 JPA 而不是普通的 Hibernate。通常,这足以让您使用。

@Repository
public class EmployeeDataDaoImpl  {


    @PersistenceContext
    private EntityManager entityManger;


    public List<Employee> findAllEmployee(){
        return em.createQuery("select e from Employee e", Employee.class).getResultList();
    }
}

使用此设置,您基本上可以完全删除 HibernateConfiguration .是的,你可以,因为 Spring Boot 会检测到 Hibernate 并自动创建一个 JpaTransactionManager , 启用交易并预配置 EntityManagerFactory .

如果你真的想使用带有 SessionFactory 的普通 hibernate 模式只需使用 HibernateJpaSessionFactoryBean暴露底层 SessionFactoryEntityManagerFactory .

@Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
    HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
    factory.setEntityManagerFactory(emf);
    return factory;
}

但是,如前所述,我强烈建议使用纯 JPA,因为它更容易设置,而且就 JPA 的当前状态而言,它提供的功能几乎与纯 Hibernate 一样多。

专业提示 您依赖于 spring-boot-starter-data-jpa这意味着您依赖于 Spring Data JPA。如果您使用 JPA,这会让事情变得更容易。您可以删除您的 EmployeeDataDaoImpl只需创建一个界面并使用它即可。

public interface EmployeeRepository extends JpaRepository<Employee, Long> {}

就是这样,所有 CRUD 方法(findOnefindAllsave 等)都已为您提供,您无需创建实现。

关于java - 需要找不到类型为 'org.hibernate.SessionFactory' 的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43533691/

相关文章:

java - android.view.InflateException : Binary XML file line #2: Binary XML file line #2: Error inflating class android. 部件.RelativeLayout

java - Android 发送电子邮件,附件错误

.net - Spring.Net 框架日落?

java - 将 org.springframework.cloud.stream.annotation 的 Spring v2 迁移到 Spring v4

java - 每当我点击按钮时 Android 应用程序就会关闭

Java比较两个有序列表: expected and actual

spring - 我如何测试在 Tomcat 中配置的数据源连接

java - 正在合并同一实体的多个表示 JPA

java - 具有不同架构的 Hibernate @Inheritance(strategy=InheritanceType.JOINED) 会导致错误(HHH000099)

java - Spring HibernateTemplate session