Spring+Hibernate,将 sessionFactory 自动装配到 hibernate DAO 中

发布于 2024-10-01 05:13:36 字数 3655 浏览 3 评论 0原文

我有一个 Hibernate DAO,根据 Hibernate API 3Spring 3.x,我只使用 sessionFactory 并且不是 HibernateDaoSupport+getHibernateTemplate() - 我希望这是一个不错的选择... -

现在我的目标是使用注释将 sessionFactory 自动连接到我的 DAO 中。

在我的 spring.xml 中,我有这样的内容:

<context:component-scan base-package="data" />

在数据包内,我拥有所有 DAO 和服务类。

这是我的简单的 HibernateDao

@Repository
public class PersonHDAO implements PersonDAO {

 private SessionFactory sessionFactory;

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

 public List<Person> findAll(){
  return sessionFactory.getCurrentSession().createQuery("bla bla").list();
 }
}

我在 spring.xml 加载期间没有错误,但 sessionFactory 仍然是 null

我必须做什么?

编辑

这是我在spring.xml中的sessionFactory声明:

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

       xsi:schemaLocation=
       "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- <property name="driverClassName" value="org.h2.Driver" /> -->
        <property name="url" value="my/db/url" />
        <property name="username" value="myUsername" />
        <property name="password" value="myPassword" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="data" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <context:component-scan base-package="data" />

    <tx:annotation-driven/>

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

</beans>

EDIT2 现在 sessionFactory 不为空,但我有另一种异常:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [data.PersonHDAO] is defined: expected single bean but found 0:

也许意味着它找不到 PersonH​​DAO bean?

谢谢大家。

i have an Hibernate DAO, in according with Hibernate API 3 and Spring 3.x, I use simply a sessionFactory and NOT an HibernateDaoSupport+getHibernateTemplate() - i hope this is a good choice... -

Now my goal is to autowire sessionFactory into my DAO using annotations.

In my spring.xml i have this:

<context:component-scan base-package="data" />

Inside data package i have all my DAO and Service classes.

This my simple HibernateDao:

@Repository
public class PersonHDAO implements PersonDAO {

 private SessionFactory sessionFactory;

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

 public List<Person> findAll(){
  return sessionFactory.getCurrentSession().createQuery("bla bla").list();
 }
}

I have no error during spring.xml loading, but sessionFactory still be null.

What i have to do?

EDIT

This is my sessionFactory declaration in spring.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:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation=
       "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- <property name="driverClassName" value="org.h2.Driver" /> -->
        <property name="url" value="my/db/url" />
        <property name="username" value="myUsername" />
        <property name="password" value="myPassword" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="data" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <context:component-scan base-package="data" />

    <tx:annotation-driven/>

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

</beans>

EDIT2
Now sessionFactory is not null, but i have another kind of exception:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [data.PersonHDAO] is defined: expected single bean but found 0:

Maybe means it can't find PersonHDAO bean?

Thanks all.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

╄→承喏 2024-10-08 05:13:36

你声明了sessionFactory bean吗?

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>file:src/hibernate.cfg.xml</value>
</property>
</bean>

Did you declare sessionFactory bean?

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>file:src/hibernate.cfg.xml</value>
</property>
</bean>
却一份温柔 2024-10-08 05:13:36

我认为你的问题是@Autowired

<前><代码>@Autowired
私有 SessionFactory 会话工厂;

I think your problem is @Autowired

@Autowired
private SessionFactory sessionFactory;
慕烟庭风 2024-10-08 05:13:36
 @Autowired
 private SessionFactory sessionFactory;

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

 public void setSessionFactory(SessionFactory sessionFactory) {
     this.sessionFactory = sessionFactory;
 }
我还不会笑 2024-10-08 05:13:36

您可以创建班级

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
@ComponentScan("com.your.package")
public class HibernateConfig {

  private Environment environment;

  @Autowired
  public void setEnvironment(Environment environment) {
    this.environment = environment;
  }

  @Bean
  public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.your.package" });
    sessionFactory.setHibernateProperties(properties());
    return sessionFactory;
  }

  @Bean
  public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("hibernate.connection.driver_class"));
    dataSource.setUrl(environment.getRequiredProperty("hibernate.connection.url"));
    dataSource.setUsername(environment.getRequiredProperty("hibernate.connection.username"));
    dataSource.setPassword(environment.getRequiredProperty("hibernate.connection.password"));
    return dataSource;
  }

  private Properties properties() {
    Properties hibernateProperties = new Properties();
    hibernateProperties.setProperty("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto",
            environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
    return hibernateProperties;
  }
}

You can create class

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
@ComponentScan("com.your.package")
public class HibernateConfig {

  private Environment environment;

  @Autowired
  public void setEnvironment(Environment environment) {
    this.environment = environment;
  }

  @Bean
  public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.your.package" });
    sessionFactory.setHibernateProperties(properties());
    return sessionFactory;
  }

  @Bean
  public DataSource dataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("hibernate.connection.driver_class"));
    dataSource.setUrl(environment.getRequiredProperty("hibernate.connection.url"));
    dataSource.setUsername(environment.getRequiredProperty("hibernate.connection.username"));
    dataSource.setPassword(environment.getRequiredProperty("hibernate.connection.password"));
    return dataSource;
  }

  private Properties properties() {
    Properties hibernateProperties = new Properties();
    hibernateProperties.setProperty("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    hibernateProperties.setProperty("hibernate.hbm2ddl.auto",
            environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
    return hibernateProperties;
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文