Java 如何解决在 Hibernate4 的 ServletContext 资源中定义名称为“sessionFactory”的 bean 时出错

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22712827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:25:53  来源:igfitidea点击:

How to resolve Error creating bean with name 'sessionFactory' defined in ServletContext resource in Hibernate4

javaspringsessiontomcatspring-mvc

提问by Aditi K

I am using Hibernate4 in my application for multitenancy implementation while building application war i got following error in my catalina of tomcat.

我在我的应用程序中使用 Hibernate4 进行多租户实现,同时构建应用程序战争我在我的 tomcat 的 catalina 中遇到了以下错误。

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: 
protected org.hibernate.SessionFactory com.boxco.blip.dao.BaseDao.sessionFactory; 
nested exception is org.springframework.beans.factory.BeanCreationException: 
Error    creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext-persistence.xml]: 
Invocation of init method failed; nested exception is java.lang.NullPointerException

Here is my application -persistance.xml

这是我的应用程序 -persistance.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">

<context:annotation-config />
<tx:annotation-driven />
<context:component-scan base-package="com.boxco.blip">
</context:component-scan>

<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName">
        <value>jdbc/blip</value>
    </property>
    <property name="resourceRef">
        <value>true</value>
    </property>
</bean>


<!-- Hibernate Session Factory  -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="annotatedClasses">
        <list>
    <value>com.boxco.blip.model.Address</value> 
        </list>
    </property>
    <property name="hibernateProperties">          
         <map>
            <entry key="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
            <entry key="hibernate.hbm2ddl.auto" value="validate" />
            <entry key="hibernate.show_sql" value="true" />
            <entry key="hibernate.connection.autocommit" value="false" />
            <entry key="hibernate.jdbc.batch_size" value="0" />
            <entry key="hibernate.connection.release_mode" value="after_transaction" />
            <entry key="hibernate.multiTenancy" value="SCHEMA" />
            <entry key="hibernate.tenant_identifier_resolver" value-ref="multiTenantIdentifierResolver1" />
            <entry key="hibernate.multi_tenant_connection_provider" value-ref="multiTenantConnectionProvider1" />      
      </map>
    </property>
</bean>

 <bean id="multiTenantConnectionProvider1" class="com.boxco.blip.web.util.SchemaMultiTenantConnectionProviderBlip">
    <property name="dataSource" ref="dataSource"/>
  </bean>
 <bean id="multiTenantIdentifierResolver1" class="com.boxco.blip.web.util.SchemaCurrentTenantIdentifierResolverBlip" />

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
    <property name="dataSource" ref="dataSource"/>
</bean>    

MY AddressDao.java File

我的 AddressDao.java 文件

package com.boxco.blip.dao;

import com.boxco.blip.model.Address;

public interface AddressDao {
   public Address getAddressByAddressId(int addressId);
 }

My AddressDaoImpl.java file

我的 AddressDaoImpl.java 文件

package com.boxco.blip.dao;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import com.boxco.blip.model.Address;
@Component
@Repository(value = "addressDao")

public class AddressDaoImpl extends BaseDao implements AddressDao {
private static final Logger logger = Logger.getLogger(AddressDaoImpl.class);

    @Override
 public Address getAddressByAddressId(int addressId) {
    logger.info("Entering getAddressByAddressId()........");
    Address address = null;
    Criteria criteria = getSession().createCriteria(Address.class);
    criteria.add(Restrictions.eq("addressId", addressId));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    address = (Address)criteria.uniqueResult();
    logger.info("Exiting getAddressByAddressId()..........");
    return address;
}

}

}

My Base Dao file where i init sessionFactory object:

我在其中初始化 sessionFactory 对象的 Base Dao 文件:

package com.boxco.blip.dao;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.mysql.jdbc.Connection;

public abstract class BaseDao 
 {

@Autowired
@Qualifier("sessionFactory")
protected SessionFactory sessionFactory;

protected void init(SessionFactory factory) {
    try {
        setSessionFactory(factory);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

public Session getSession() throws HibernateException {
    // return sessionFactory.getCurrentSession();
    return sessionFactory.withOptions().tenantIdentifier("BLIP1314ERP")
            .openSession();
}

     //some more methods
  }

My Dispatcher-servlet.xml file where is added

我的 Dispatcher-servlet.xml 文件在哪里添加

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="...">

<mvc:annotation-driven/>

<context:component-scan base-package="com.boxco">
    <!-- <context:exclude-filter type="regex" expression="com.boxco.blip.dao.*" /> -->
</context:component-scan>

<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
    <property name="basenames" value="views"/>

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <value>messages,error_codes</value>
    </property>
</bean> 

<bean id="validatorFactory"
      class="org.springmodules.validation.commons.DefaultValidatorFactory">
    <property name="validationConfigLocations">
        <list>
            <value>/WEB-INF/validator-rules.xml</value>
            <value>/WEB-INF/validator.xml</value>
            <value>/WEB-INF/validatorFas.xml</value>
            <value>/WEB-INF/validatorFas-rules.xml</value>
        </list>
    </property>
</bean>

<bean id="validator" class="org.springmodules.validation.commons.DefaultBeanValidator">
    <property name="validatorFactory" ref="validatorFactory"/>
</bean>     

Error is in my SessionFactoryinitialization but why it is not getting init is my problem..? (I am handling this error first time)..

错误在我的SessionFactory初始化中,但为什么它没有得到 init 是我的问题..?(我是第一次处理这个错误)。

Any suggestion appreciated.

任何建议表示赞赏。

回答by Pirulino

It shouldn't be your solution, in any case the @component annotation over @repository is useless. Either you insert @repository (better for exception translation) or @component.

它不应该是您的解决方案,无论如何@repository 上的@component 注释是无用的。要么插入@repository(更适合异常翻译)或@component。

回答by Aditi K

I resolved it by replacing my JAR files from 4.3.4 to 4.1.7 (downgraded my jar) hibernate version ,I dont know why its not working with latest versions of Hibernate

我通过将我的 JAR 文件从 4.3.4 替换为 4.1.7(降级我的 jar)休眠版本来解决它,我不知道为什么它不能与最新版本的 Hibernate 一起使用