0

Есть прстое хранилище которое должно использовать HibernateTemplate для сохранения данных в таблицу. Но Spring не создает его bean отказываясь автоматически подтягивать HibernateTemplate. Помогите пожалуйста разобраться как это поправить.

Вот такая ошибка:

[main] WARN org.springframework.context.support.ClassPathXmlApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'HItemStorage' defined in file [/Users/pavel/GitHub/Spring-data-Hibernate/target/classes/ru/pravvich/HItemStorage.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.orm.hibernate4.HibernateTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'HItemStorage' defined in file [/Users/pavel/GitHub/Spring-data-Hibernate/target/classes/ru/pravvich/HItemStorage.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.orm.hibernate4.HibernateTemplate' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

@Component
public class HItemStorage implements Storage {

    private final HibernateTemplate template;

    @Autowired
    public HItemStorage(HibernateTemplate template) {
        this.template = template;
    }

    @Override
    public List<Item> getAll() {
        return (List<Item>) template.find("from Item");
    }
    ...
}

Используется вот такой конфигурационный файл:

<?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: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/context
                            http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Database properties -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://127.0.0.1:5432/spring_jdbc" />
        <property name="username" value="postgres" />
        <property name="password" value="1" />
    </bean>

    <!-- Connecting template -->
    <bean id="template" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />

        <property name="mappingResources">
            <list>
                <value>ru/pravvich/Item.hbm.xml</value>
            </list>
        </property>

        <!-- Hibernate properties -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL94Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <context:component-scan base-package="ru.pravvich" />

</beans>

Получается прописанный class="...LocalSessionFactoryBean" не срабатывает?

Падает при

final ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("hibernate-context.xml");

Даже не доходит до:

HItemStorage storage = context.getBean(HItemStorage.class);

1 ответ 1

1

так template бин у вас имеет класс LocalSessionFactoryBean, а спринг вытается найти бин template с классом HibernateTemplate

судя по этому посту : https://stackoverflow.com/questions/9780585/creating-hibernatetemplate-by-org-springframework-orm-hibernate4-localsessionfac

Использовать HibernateTemplate не рекомендуется с 3,0,1 версии. И там же предлагают использовать SessionFactoryImpl

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'sessionFactory' must be of type [org.springframework.orm.hibernate4.LocalSessionFactoryBean], but was actually of type [org.hibernate.internal.SessionFactoryImpl]

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.