需要一个类型' org.hibernate.SessionFactory'无法找到

时间:2017-04-21 03:54:44

标签: java spring hibernate maven spring-boot

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

申请失败

说明

com.base.model.AbstractDao中的字段会话需要一个类型为' 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>

application.property

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

}

Employee.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 + "]";
    }
}

Employee.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上查找了相同的错误代码,但没有一个解决方案有效,因此我的代码再次在此处发布。 希望别人可以指出我哪里出错了。

2 个答案:

答案 0 :(得分:13)

对于初学者来说,您的配置有几个方面

  1. 混合来自不同Spring和Hibernate版本的jar
  2. 太可能已经管理了依赖项
  3. 尝试比Spring Boot更聪明。
  4. 对于1.和2.只需移除<version>的{​​{1}}标记以及spring-ormhibernate-core经理依赖关系。 Spring Boot已经在管理这些了。实际上,你可以删除那些已被初学者拉入的hibernate-entitymanager依赖项(实际上也是hibernate的依赖项)。

    org.springframework

    接下来,在您的配置中,您至少配置了<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> 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的普通休眠,只需使用HibernateJpaSessionFactoryBean来展示SessionFactory的基础EntityManagerFactory

    @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等)都是为您提供的,无需您创建实现。

答案 1 :(得分:3)

您的SessionFactory配置错误。从你的pom.xml我看到你正在使用hibernate版本5,所以你的配置应该是:

spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext

你的pom.xml中也有不同版本的hibernate jar,尝试使用相同的版本。