8

我是 Spring 新手,我正在尝试使用以下堆栈创建一个 webapp:Apache Tomcat 7、MySQL、Spring MVC、带有 JPA 注释的 Hibernate 3。

我正在尝试通过阅读 Craig Walls 的《Spring in Action,第三版》一书来学习。

首先,我想创建一个页面来显示我手动添加到数据库中的一些条目,但看起来我的应用程序无法从我的 SessionFactory 创建/检索任何 Hibernate Session。这是我的根本原因堆栈跟踪:

exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

root cause

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)
    org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687)
    com.nbarraille.www.dao.HibernateContactDAO.listContact(HibernateContactDAO.java:27)
    com.nbarraille.www.controllers.HomeController.showHomePage(HomeController.java:24)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:613)
    org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426)
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

这是我关心的类/配置文件:

我的 HibernateDAO:

@Repository
public class HibernateContactDAO implements ContactDAO {

    private SessionFactory sessionFactory;

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

    public void addContact(Contact contact) {
        sessionFactory.getCurrentSession().save(contact);
    }

    public List<Contact> listContact() {
        @SuppressWarnings("unchecked")
        List<Contact> cl = sessionFactory.getCurrentSession().createQuery("from Contact").list();
        return cl;
    }

    public void removeContact(Integer id) {
        Contact contact = (Contact) sessionFactory.getCurrentSession().load(Contact.class, id);
        if (null != contact) {
            sessionFactory.getCurrentSession().delete(contact);
        }

    }
}

我的联系方式:

@Entity
@Table(name="contacts")
public class Contact implements Serializable {
    private static final long serialVersionUID = -5389913432051078273L;

    @Id
    @Column(name="id")
    @GeneratedValue
    private int id;

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

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

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

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


    // Setters/Getters
}

我的控制器类:

@Controller

    public class HomeController {

        private ContactDAO contactDAO; // I know I should pass through a service instead of accessing my DAO directly, and I usually do, but I skipped it here to simplify and try to locate the problem

        @Inject
        public HomeController(ContactDAO contactDAO){
            this.contactDAO = contactDAO;
        }

        @RequestMapping({"/", "/home"})
        public String showHomePage(Map<String,Object> model){
            model.put("contacts", contactDAO.listContact());
            return "index";
        }
    }

这是我的上下文数据配置文件:

<bean id="DBpropertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="/WEB-INF/jdbc.properties" />
    </bean>

<bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/nbarraille" />
    <property name="username" value="root" />
    <property name="password" value="password" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.nbarraille.www.core" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <!-- Adds an advisor to any bean annotated with @Repository so that any platform-specific exception
         are caught and then rethrown as one of Spring's unchecked data access exceptions -->
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

这是我的 Dispatcher Servlet 配置:

<mvc:resources mapping="/resources/**"
                   location="/resources/" />

<mvc:annotation-driven />

<context:component-scan base-package="com.nbarraille.www" />

<bean class="org.springframework.web.servlet.view.tiles2.TilesViewResolver" />

<bean class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles-def.xml</value>
            </list>
        </property>
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="lang" />
    </bean>

    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en"/>
    </bean>

最后,这是我的 web.xml 文件:

<servlet>
    <servlet-name>nbarraille</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>nbarraille</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/nbarraille-service.xml
        /WEB-INF/nbarraille-data.xml
        /WEB-INF/nbarraille-security.xml
    </param-value>
</context-param>
4

3 回答 3

12

您似乎还没有配置事务...您可以将以下内容添加到您的上下文数据配置文件中:-

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

<tx:advice id="txAdvice">
    <tx:attributes>
        <tx:method name="*" propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>

<aop:config>
    <aop:advisor pointcut="execution(* YOUR.PACKAGE..*.*(..))" advice-ref="txAdvice" />
</aop:config>

将 YOUR.PACKAGE更改为您的实际包名称,例如:-

execution(* com.project..*.*(..))

这是一种用事务将项目中的所有方法包装起来的懒惰方式。

顺便说一句,如果您要parent.getChildren()在视图中懒惰地查询您的 Hibernate 域对象(例如:),那么我强烈建议您将其添加到您的 web.xml 中:-

<filter>
    <filter-name>hibernateFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>hibernateFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

此过滤器将 Hibernate 会话扩展到视图。

于 2011-02-25T19:47:48.747 回答
0

我今天也有同样的问题。它与hibernate工作单元概念和数据库事务相关。所以简短地说。如果您使用框架 spring,它有自己的事务管理器和会话工厂实现。但是如果你想使用它,你应该记住配置它,但也要正确的注解顺序。你的服务应该是@Transactional,你的DAO 应该是@Repository 并且DAO 使用@Entity bean。因此,如果您要使用事务管理器的 spring 实现,则应该在控制器中使用事务服务;)这非常简单,并且在您的 dao 中您执行 sessionfactory.getCurrentSession() 来获取会话;)

于 2013-03-28T22:37:53.247 回答
0

对于它的价值......也遇到了这个问题,经过大量查看后不得不修改 web.xml 的一部分:

    <filter>
    <filter-name>hibernateFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
    <init-param>
        <param-name>singleSession</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

...特别是必须将singleSession设置为true

于 2011-02-25T19:56:55.953 回答