简体   繁体   English

无法自动连线字段:私有org.hibernate.SessionFactory Hibernate和Spring

[英]Could not autowire field: private org.hibernate.SessionFactory Hibernate and Spring

I got this error after deploying project on my server Tomcat. 在服务器Tomcat上部署项目后出现此错误。 I found many similar questions but I did not found answer for my problem. 我发现了许多类似的问题,但没有找到解决问题的答案。

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'categoryDaoDbImpl': Injection of autowired dependencies failed; org.springframework.beans.factory.BeanCreationException:创建名称为'categoryDaoDbImpl'的bean时出错:自动连接依赖项的注入失败; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory ua.com.goit.gojava7.kikstarter.dao.database.CategoryDaoDbImpl.sessionFactory; 嵌套的异常是org.springframework.beans.factory.BeanCreationException:无法自动连线字段:私有org.hibernate.SessionFactory ua.com.goit.gojava7.kikstarter.dao.database.CategoryDaoDbImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; 嵌套异常是org.springframework.beans.factory.BeanCreationException:创建在类路径资源[applicationContext.xml]中定义的名称为'sessionFactory'的bean时出错:调用init方法失败; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on ua.com.goit.gojava7.kikstarter.domain.Payment.projectId references an unknown entity: int at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.b 嵌套的异常是org.hibernate.AnnotationException:ua.com.goit.gojava7.kikstarter.domain.Payment.projectId上的@OneToOne或@ManyToOne引用了一个未知实体:org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues处的int (AutowiredAnnotationBeanPostProcessor.java:334)在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)在org.springframework.beans.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)在org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:305)在org.springframework.beans.factory org.springframework.b上的.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) eans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:835) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) org.springframework.beans.beans.factory.support.DefaultListableBeanFactory上的eans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)在org.springframework.beans.factory.support.DefaultListableBeanFactory。 org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)上的org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:835)上的preInstantiateSingletons(DefaultListableBeanFactory.java:772) org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328)位于org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java)的.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446) :107)

applicationContext.xml applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/tx    
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd">

    <context:property-placeholder location="classpath:config.properties" />
    <context:component-scan base-package="ua.com.goit.gojava7.kikstarter.dao.database" />

    <bean id="basicDataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.dataBaseUrl}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

        <property name="dataSource">
            <ref bean="basicDataSource" />
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>

        <property name="annotatedClasses">
            <list>
                <value>ua.com.goit.gojava7.kikstarter.domain.Quote</value>
                <value>ua.com.goit.gojava7.kikstarter.domain.Category</value>
                <value>ua.com.goit.gojava7.kikstarter.domain.Project</value>
                <value>ua.com.goit.gojava7.kikstarter.domain.Payment</value>
                <value>ua.com.goit.gojava7.kikstarter.domain.Reward</value>
            </list>
        </property>
    </bean>

the CategoryDaoDbImpl class CategoryDaoDbImpl类

package ua.com.goit.gojava7.kikstarter.dao.database;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Criteria;

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

import ua.com.goit.gojava7.kikstarter.dao.CategoryDao;
import ua.com.goit.gojava7.kikstarter.domain.Category;

@Repository
public class CategoryDaoDbImpl implements CategoryDao {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    @Transactional
    @Override
    public List<Category> getAll() {
        Session session=sessionFactory.openSession();

        Criteria criteria=session.createCriteria(Category.class);
        List<Category> categories=criteria.list();

        session.close();
        return categories;
    }

    @Transactional
    @Override
    public Category getCategory(int id) {
        Session session=sessionFactory.openSession();

        Criteria criteria=session.createCriteria(Category.class);
        criteria.add(Restrictions.eq("id", id));
        Category category=(Category) criteria.uniqueResult();

        session.close();
        return category;
    }
}

the Category class 类别类

package ua.com.goit.gojava7.kikstarter.domain;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "categories")
public class Category {

    @Id
    @SequenceGenerator(name = "SEQ_GEN", sequenceName = "seq_id", allocationSize = 10)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GEN")
    private int id;

    @Column(name = "name")
    private String name;

    @OneToMany
    private Set<Project> projects;

    public int getId() {
        return id;
    }

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

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

    public String getName() {
        return name;
    }

    public Set<Project> getProjects() {
        return projects;
    }

    public void setProjects(Set<Project> projects) {
        this.projects = projects;
    }

    @Override
    public String toString() {
        return "ID: " + id + "; Name: " + name;
    }
}

the Project class 项目类

package ua.com.goit.gojava7.kikstarter.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "projects")
public class Project {

    @Id
    @SequenceGenerator(name = "SEQ_GEN", sequenceName = "seq_id", allocationSize = 10)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_GEN")
    private int id;

    @ManyToOne
    @JoinColumn(name = "category_id")
    private Category category;

    @Column(name = "name")
    private String name;

    @Column(name = "general_description")
    private String generalDescription;

    @Column(name = "full_description")
    private String fullDescription;

    @Column(name = "video_link")
    private String videoLink;

    @Column(name = "required_sum")
    private int requiredSum;

    @Column(name = "collected_sum")
    private int collectedSum;

    @Column(name = "days_left")
    private int endOfDays;

    public int getId() {
        return id;
    }

    public Category getCategory() {
        return category;
    }

    public String getName() {
        return name;
    }

    public String getGenerelDescription() {
        return generalDescription;
    }

    public String getFullDescription() {
        return fullDescription;
    }

    public String getVideoLink() {
        return videoLink;
    }

    public int getRequiredSum() {
        return requiredSum;
    }

    public int getCollectedSum() {
        return collectedSum;
    }

    public int getEndOfDays() {
        return endOfDays;
    }

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

    public void setCategory(Category category) {
        this.category = category;
    }

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

    public void setGeneralDescription(String generalDescription) {
        this.generalDescription = generalDescription;
    }

    public void setFullDescription(String fullDescription) {
        this.fullDescription = fullDescription;
    }

    public void setVideoLink(String videoLink) {
        this.videoLink = videoLink;
    }

    public void setRequiredSum(int requiredSum) {
        this.requiredSum = requiredSum;
    }

    public void setCollectedSum(int collectedAmount) {
        this.collectedSum = collectedAmount;
    }

    public void setSumFromUser(int enteredAmount) {
        collectedSum += enteredAmount;
    }

    public void setEndOfDays(int endOfDays) {
        this.endOfDays = endOfDays;
    }

    @Override
    public String toString() {
        return "Project: name: " + name + "; general description: " + generalDescription + "; full description: "
            + fullDescription + "; video link: " + videoLink + "; required sum: " + requiredSum
            + "; collected sum: " + collectedSum + "; days left: " + endOfDays;
    }
}

This would have been too long for a comment and based on your comment I think it might help to give you a longer explanation. 这对于评论来说太长了,根据您的评论,我认为这可能有助于给您更长的解释时间。

When reading Java exceptions there are a couple of things to keep in mind. 在阅读Java异常时,有几件事要牢记。

  1. The Stack . 堆栈 Code execution is tracked by adding 'frames' to the stack. 通过向堆栈添加“框架”来跟踪代码执行。 Every time you call a method, a new frame is 'pushed' onto the stack. 每次调用方法时,都会将一个新框架“推入”堆栈。 This is how, when an exception is thrown, you are able to get the methods that were called that led up to the exception (called the Stack Trace ). 这样,当引发异常时,您就能获得导致异常的被调用方法(称为Stack Trace )。
  2. Chained Exceptions . 链式异常 In Java, when an exception is thrown, it is possible to specify the 'cause' of the exception. 在Java中,当引发异常时,可以指定异常的“原因”。 It is a way of keeping track of the Stack Trace of the exception that 'caused' the new exception that is being thrown. 这是一种跟踪“导致”所引发的新异常的异常的堆栈跟踪的方法。

The Spring Framework is notorious for liberally using chained exceptions (and I personally think this is a good quality), which makes reading the errors returned from the framework a little tricky. Spring框架因自由使用链式异常而臭名昭著(我个人认为这是一种很好的品质),这使得读取框架返回的错误变得有些棘手。 What makes it tricky is that the order of the Stack Trace and the order of the Chained Exceptions are essentially reversed . 棘手的是,堆栈跟踪的顺序和链接异常的顺序实际上是相反的

That is to say that with the Stack Trace, the most recently executed code is at the top. 也就是说,使用堆栈跟踪,最近执行的代码位于顶部。 However, with the chained exceptions, the 'first' exception that was thrown is at the bottom. 但是,使用链接的异常,引发的“第一个”异常在底部。

So what you need to do is look for the 'first' exception that was thrown to find the real root cause of the exception and fix that one. 因此,您需要做的是查找抛出的“第一个”异常,以找到异常的真正根本原因并修复该异常。 There is a pretty good question/answer already on SO that further explains what I'm talking about. 在SO上已经有一个很好的问题/答案,可以进一步解释我在说什么。

So looking at your specific example (and simplifying it to call out the structure you need to pay attention to) we see: 因此,查看您的特定示例(并将其简化为需要注意的结构),我们看到:

BeanCreationException: Error creating bean with name 'categoryDaoDbImpl': Injection of autowired dependencies failed; **nested exception is**
|
|-> BeanCreationException: Could not autowire field: private SessionFactory CategoryDaoDbImpl.sessionFactory; **nested exception is**
    |
    |-> BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; **nested exception is**
        |
        |-> AnnotationException: @OneToOne or @ManyToOne on Payment.projectId references an unknown entity: int at
                org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at 
                org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) at
                org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) at 
                org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at 
                org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) at 
                org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at 
                org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) at 
                org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) at 
                org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) at 
                org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:835) at 
                org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) at 
                org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:446) at 
                org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:328) at 
                org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)

When you see nested exception is , you are dealing with Chained Exceptions. 当看到嵌套异常是时 ,您正在处理链式异常。 So, what you actually have is one exception that is causing your problem, and that is a problem with the mapping on your Payment object; 因此,您实际拥有的是一个导致您出现问题的异常,这是您的Payment对象上的映射存在问题。 specifically the projectId field. 特别是projectId字段。

So when you ask 所以当你问

What about Could not autowire field: private org.hibernate.SessionFactory and Error creating bean with name 'categoryDaoDbImpl' I have to create bean with name 'categoryDaoDbImpl' in file applicationContext.xml? 关于无法自动连接字段:私有org.hibernate.SessionFactory和创建名称为'categoryDaoDbImpl'的bean时出错我必须在文件applicationContext.xml中创建名称为'categoryDaoDbImpl'的bean吗?

Hopefully it is now clear that you don't have to do anything about the "first" three BeanCreationException because those are all caused by the root AnnotationException 希望现在很清楚,您不必对“前”三个BeanCreationException做任何事情,因为这些都是AnnotationException 引起的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 org.springframework.beans.factory.BeanCreationException:无法自动连线字段:私有org.hibernate.SessionFactory - org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory 无法使用Spring 5自动连接休眠5 sessionfactory - Could not autowire hibernate 5 sessionfactory with spring 5 Spring Hibernate:没有匹配的org.hibernate.SessionFactory类型的bean - Spring Hibernate : No matching bean of type org.hibernate.SessionFactory 找不到类型为“ org.hibernate.SessionFactory”的bean - A bean of type 'org.hibernate.SessionFactory' that could not be found 需要一个无法找到的&#39;org.hibernate.SessionFactory&#39;类型的bean - required a bean of type 'org.hibernate.SessionFactory' that could not be found 春天启动。无法找到“org.hibernate.SessionFactory”类型的bean - Spring-boot. A bean of type 'org.hibernate.SessionFactory' that could not be found Bean必须为&#39;org.hibernate.SessionFactory&#39;类型 - Bean must be of 'org.hibernate.SessionFactory' type 没有类型[org.hibernate.SessionFactory]的限定bean - No qualifying bean of type [org.hibernate.SessionFactory] 类型构造函数的参数 0 需要一个无法找到的类型为“org.hibernate.SessionFactory”的 bean - Parameter 0 of constructor in type required a bean of type 'org.hibernate.SessionFactory' that could not be found 考虑在您的配置中定义一个“org.hibernate.SessionFactory”类型的 bean。 - 春天 - Consider defining a bean of type 'org.hibernate.SessionFactory' in your configuration. - Spring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM