需要一个无法找到的'org.hibernate.SessionFactory'类型的bean [英] required a bean of type 'org.hibernate.SessionFactory' that could not be found
问题描述
$ b
APPLICATION FAILED TO START
描述:
com.base中的字段会话.model.AbstractDao需要一个无法找到的'org.hibernate.SessionFactory'类型的bean。
动作:
考虑在您的配置中定义一个类型为'org.hibernate.SessionFactory'的bean。
我添加了我的应用程序的实现:
POM.xml
<?xml version = 1.0encoding =UTF-8?>
< project xmlns =http://maven.apache.org/POM/4.0.0xmlns: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>
<包装> jar< / packaging>
< name>演示< / name>
< description> Spring Boot的演示项目< / description>
< parent>
< groupId> org.springframework.boot< / groupId>
< artifactId> spring-boot-starter-parent< / artifactId>
< version> 1.5.2.RELEASE< / version>
< relativePath /> <! - 从存储库查找父级 - >
< / parent>
<属性>
< project.build.sourceEncoding> UTF-8< /project.build.sourceEncoding>
< project.reporting.outputEncoding> UTF-8< /project.reporting.outputEncoding>
< java.version> 1.8< /java.version>
< / properties>
<依赖关系>
< dependency>
< groupId> org.springframework.boot< / groupId>
< artifactId> spring-boot-starter-web< / artifactId>
< /依赖关系>
<! - Spring - >>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-core< / artifactId>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-context< / artifactId>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-tx< / artifactId>
< /依赖关系>
< dependency>
< groupId> org.springframework< / groupId>
< artifactId> spring-orm< / artifactId>
< version> 4.2.2.RELEASE< / version>
< /依赖关系>
< dependency>
< groupId> org.springframework.boot< / groupId>
< artifactId> spring-boot-starter-test< / artifactId>
< scope> test< / scope>
< /依赖关系>
<! - Hibernate dependency - >
< dependency>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-core< / artifactId>
< version> 5.1.5.Final< / version>
< /依赖关系>
< dependency>
< groupId> org.hibernate< / groupId>
< artifactId> hibernate-entitymanager< / artifactId>
< version> 5.0.3.Final< / version>
< /依赖关系>
< dependency>
< groupId> mysql< / groupId>
< artifactId> mysql-connector-java< / artifactId>
< /依赖关系>
< dependency>
< groupId> org.springframework.boot< / groupId>
< artifactId> spring-boot-starter-data-jpa< / artifactId>
< /依赖关系>
< /依赖关系>
< 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。属性))
公共类HibernateConfiguration {
@Autowired
私有环境;
@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
公共属性hibernateProperties(){
属性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));
返回属性;
@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));
返回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;
私人字符串名称;
私人字符串国家;
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();
$ b @覆盖
public String toString(){
returnEmployee [id =+ id +,name =+ name +,country =
+ country +];
}
}
Employee.hbm.xml
<?xml version ='1.0'encoding ='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
- // Hibernate / Hibernate映射DTD 3.0 // EN
http://www.hibernate.org/dtd/hibernate-mapping -3.0.dtd>
< hibernate-mapping>
< class name =com.base.model.Employeetable =Person>
< id name =idtype =java.lang.Integer>
< generator class =native>< / generator>
< / id>
< property name =nametype =java.lang.String>
< column name =namenot-null =true>< / column>
< / property>
< property name =countrytype =java.lang.String>
< column name =country>< / column>
< / property>
< / class>
< / hibernate-mapping>
EmployeeDaoImpl
@Component
public class EmployeeDataDaoImpl {
@Autowired
SessionFactory sessionFactory;
公共列表<员工> findAllEmployee(){
//// Criteria cri = getSession()。createCriteria(Employee.class);
//清单<员工> dbList = cri.list();
// for(Employee employee:dbList){
// System.out.println(employee.getCountry());
//}
返回null;
}
}
我查了同样的错误代码在stackoverflow但没有解决方案工作,因此张贴在这里再次与我的代码。
希望别人能指出我要去的地方有什么问题。
- 混合来自不同Spring和Hibernate版本的jar
- / li>
- 试着更聪明地使用Spring Boot。
对于1.和2.只需删除< version>
标签用于 spring-orm
和 hibernate-core
和 hibernate-entitymanager
管理器依赖关系。 Spring Boot已经在管理这些。实际上你可以删除所有已经被初学者拉入的 org.springframework
依赖关系(实际上也是休眠类)。
<依赖关系>
< dependency>
< groupId> org.springframework.boot< / groupId>
< artifactId> spring-boot-starter-web< / artifactId>
< /依赖关系>
< dependency>
< groupId> org.springframework.boot< / groupId>
< artifactId> spring-boot-starter-data-jpa< / artifactId>
< /依赖关系>
< dependency>
< groupId> org.springframework.boot< / groupId>
< artifactId> spring-boot-starter-test< / artifactId>
< scope> test< / scope>
< /依赖关系>
< dependency>
< groupId> mysql< / groupId>
< artifactId> mysql-connector-java< / artifactId>
< /依赖关系>
< /依赖关系>
接下来在配置中至少有2个 SessionFactory
的配置。我建议使用注释来定义实体,而不是 hbm.xml
文件。
pre $ @Entity
@Table(person)
public class Employee实现Serializable {
/ **
*
* /
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private int id;
@Column(nullable = false)
私有字符串名称;
私人字符串国家;
$ b当使用JPA注解时,Hibernate会自动检测你的实体(尤其是结合Spring Boot),这使得它非常强大。您现在可以删除 Employee.hbm.xml
。
接下来您的 EmployeeDataDaoImpl
我强烈建议在普通的Hibernate上使用普通的JPA。一般来说,这为您提供了足够的帮助。
@Repository
public class EmployeeDataDaoImpl {
@PersistenceContext
private EntityManager entityManger;
公共列表<员工> findAllEmployee(){
return em.createQuery(select e from Employee e,Employee.class).getResultList();
$ b $ p
$ b 使用这个设置你可以基本上完全删除你的 HibernateConfiguration
。是的,您可以像Spring Boot检测到Hibernate并自动创建 JpaTransactionManager
,启用事务并预先配置 EntityManagerFactory
。
如果你真的想用 SessionFactory
来使用纯休眠,只需使用 HibernateJpaSessionFactoryBean
来展示 EntityManagerFactory
的底层 SessionFactory
。
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf){
HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
factory.setEntityManagerFactory(emf);
退货工厂;
}
然而,如上所述,我强烈建议使用普通JPA,因为这是很多更容易设置,并且与JPA的当前状态一样,它提供的功能几乎与普通的Hibernate一样多。
专业提示
您依赖于 spring-boot-starter-data-jpa
这意味着您对Spring Data JPA有依赖性。如果你使用JPA,这会让事情变得更容易。你可以删除你的 EmployeeDataDaoImpl
并创建一个接口并使用它。
pre $ public interface EmployeeRepository扩展JpaRepository< Employee,Long> {}
就是这样,所有的CRUD方法( findOne
, findAll
, save
等)不需要创建实现。 / p>
I am getting following error whenever started application spring boot.
APPLICATION FAILED TO START
Description:
Field session in com.base.model.AbstractDao required a bean of type 'org.hibernate.SessionFactory' that could not be found.
Action:
Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration.
I have added implementation of my application:
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 class
@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;
}
}
I have looked up the same error code on stackoverflow but none of the solutions worked and thus posting it here again with my code. Hoping someone else can point out where I am going wrong.
For starters there are a couple of things of with your configuration
- Mixing jars from different Spring and Hibernate versions
- Too may already managed dependencies
- Trying to be smarter then Spring Boot.
For 1. and 2. just remove the <version>
tag for spring-orm
and the hibernate-core
and hibernate-entitymanager
manager dependencies. Spring Boot is already managing those. You can actually remove all the org.springframework
dependencies those are already pulled in by the starters (and actually the hibernate ones also).
<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>
Next in your configuration you have at least 2 SessionFactory
's configured. I would suggest to use annotations to define your entities instead of hbm.xml
files.
@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;
}
When using JPA annotations Hibernate will automatically detect your entities (especially combined with Spring Boot) which makes it very powerful. Ofcourse you can now remove your Employee.hbm.xml
.
Next your EmployeeDataDaoImpl
I strongly suggest to use plain JPA over plain Hibernate. Generally that provides enough for you to work with.
@Repository
public class EmployeeDataDaoImpl {
@PersistenceContext
private EntityManager entityManger;
public List<Employee> findAllEmployee(){
return em.createQuery("select e from Employee e", Employee.class).getResultList();
}
}
With this setup you can basically completely remove your HibernateConfiguration
. Yes you can as Spring Boot detects Hibernate and automatically creates a JpaTransactionManager
, enables transactions and preconfigured a EntityManagerFactory
.
If you really want to use plain hibernate with a SessionFactory
just use a HibernateJpaSessionFactoryBean
to expose the underlying SessionFactory
of the EntityManagerFactory
.
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
factory.setEntityManagerFactory(emf);
return factory;
}
However as mentioned I would strongly suggest to use plain JPA as that is a lot easier to setup and with the current state of JPA it offers almost as much of the functionality as plain Hibernate does.
Pro Tip
You have a dependency on spring-boot-starter-data-jpa
which means you are having a dependency on Spring Data JPA. Which would make things even easier if you would use JPA. You can remove your EmployeeDataDaoImpl
and just create an interface and use that.
public interface EmployeeRepository extends JpaRepository<Employee, Long> {}
That is it, all the CRUD methods (findOne
, findAll
, save
etc.) are provided for you without you having to create an implementation.
这篇关于需要一个无法找到的'org.hibernate.SessionFactory'类型的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!