简体   繁体   中英

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

I got this error after deploying project on my server 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; 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; 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; 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 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)

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

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.

  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 ).
  2. Chained Exceptions . In Java, when an exception is thrown, it is possible to specify the 'cause' of the exception. 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. 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 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; specifically the projectId field.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM