0

我的 application-context.xml :

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

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>
    <property name="url"><value>jdbc:mysql://localhost:3306/myDB</value></property>
    <property name="username"><value>myUser</value></property>
    <property name="password"><value>myPwd</value></property>

</bean>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>                            
    <property name="mappingResources">
<list>
<value>user.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties" >
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
</value>
</property>
</bean>


<bean id="userdao" class="x.y.z.UserDao">
<property name="sessionFactory" ref="mySessionFactory"/>

</bean>

     </beans>

用户.hbm.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="x.y.m">
<class name="User" table="user">
<id name="userId" column="id">
     <generator class="native"/>
</id>

 <property name="firstname" column="firstName" />
 <property name="lastName" column="lastName"/>
 <property name="login" column="login"/>
 <property name="pass" column="pass"/>
 <property name="superemail" column="superEmail"/>
 </class>

</hibernate-mapping>

用户道.java:

package x.y.z;


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import x.y.m.User;


@Component
public class UserDao {

    SessionFactory sessionFactory;

    public void addUser(User user) {
        Session session;
        try {
            try {

                session = this.sessionFactory.getCurrentSession();

            System.out.println(session.isConnected());
                session.save(user);
            } catch (RuntimeException e) {
                System.out.println("Not Getting Session");
                // TODO Auto-generated catch block

                e.printStackTrace();
            }
        } catch (HibernateException e) {
            // TODO Auto-generated catch block
            System.out.println("printing in the catch");
            e.printStackTrace();
        }

    }

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

    }

}

用户控制器.java:

  package x.y.c.a;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;


    import x.y.z.UserDao;
    import x.y.m.User;


    @Controller
    public class UserController  {
        @Autowired UserDao userdao ;
        @RequestMapping(value = "/user", method = RequestMethod.GET)
           public ModelAndView student() {
              return new ModelAndView("user", "command", new User());
           }

           @RequestMapping(value = "/addUser", method = RequestMethod.POST)
           public String addStudent(@ModelAttribute("SpringWeb")User user, 
           ModelMap model) {
              model.addAttribute("userId", user.getUserId());
              model.addAttribute("login", user.getLogin());
              model.addAttribute("pass", user.getPass());
              model.addAttribute("firstname", user.getFirstname());
              model.addAttribute("lastName", user.getLastName());
              model.addAttribute("superemail", user.getSuperemail());

            //  UserDao u = new UserDao();
              System.out.println("u==null = "+ userdao==null);
             // System.out.println("u.getSessionFactory()==null = "+ userdao.getSessionFactory()==null);
              userdao.addUser(user);
             // userdao.addUser(user.getId(),user.getLogin(),user.getPass(),user.getFirstname(),user.getLastname(),user.getSuperemail());
              return "result";
           }

           /**
             * @return Returns the userdao.
             */
            public UserDao getUserdao() {
                return userdao;
            }
            /**
             * @param userdao The userdao to set.
             */
            public void setUserdao(UserDao userdao) {
                System.out.println("setting user dao ");
                this.userdao = userdao;
            }

    }

尝试添加用户记录时,我不断收到以下异常:

20:13:44,433 INFO  [STDOUT] Not Getting Session
20:13:44,434 ERROR [STDERR] java.lang.NullPointerException
20:13:44,436 ERROR [STDERR]     at com.cpt.dao.assessment.UserDao.addUser(UserDao.java:41)
20:13:44,437 ERROR [STDERR]     at com.cpt.controller.assessment.UserController.addStudent(UserController.java:42)
20:13:44,437 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
20:13:44,439 ERROR [STDERR]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
20:13:44,440 ERROR [STDERR]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
20:13:44,440 ERROR [STDERR]     at java.lang.reflect.Method.invoke(Method.java:601)
20:13:44,441 ERROR [STDERR]     at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
20:13:44,442 ERROR [STDERR]     at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436)
20:13:44,443 ERROR [STDERR]     at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424)

20:13:44,444 ERROR [STDERR]     at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:950)
20:13:44,444 ERROR [STDERR]     at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:859)
20:13:44,445 ERROR [STDERR]     at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:883)
20:13:44,445 ERROR [STDERR]     at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:792)
20:13:44,445 ERROR [STDERR]     at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
20:13:44,446 ERROR [STDERR]     at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
20:13:44,446 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:324)
20:13:44,447 ERROR [STDERR]     at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242)
20:13:44,447 ERROR [STDERR]     at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
20:13:44,448 ERROR [STDERR]     at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
20:13:44,448 ERROR [STDERR]     at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:181)
20:13:44,448 ERROR [STDERR]     at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.event(CatalinaContext.java:285)
20:13:44,449 ERROR [STDERR]     at org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.invoke(CatalinaContext.java:261)
20:13:44,449 ERROR [STDERR]     at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:88)
20:13:44,450 ERROR [STDERR]     at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:100)
20:13:44,450 ERROR [STDERR]     at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
20:13:44,451 ERROR [STDERR]     at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
20:13:44,451 ERROR [STDERR]     at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)20:13:44,452 ERROR [STDERR]     at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
20:13:44,452 ERROR [STDERR]     at org.jboss.web.tomcat.service.request.ActiveRequestResponseCacheValve.invoke(ActiveRequestResponseCacheValve.java:53)
20:13:44,452 ERROR [STDERR]     at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362)
20:13:44,453 ERROR [STDERR]     at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
20:13:44,453 ERROR [STDERR]     at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:654)
20:13:44,454 ERROR [STDERR]     at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:951)
20:13:44,455 ERROR [STDERR]     at java.lang.Thread.run(Thread.java:722)

请帮忙。

4

2 回答 2

1

Decalre 一个事务管理器(我使用休眠):

<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager"/>

<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>

然后将方法或类注释为transactional

于 2012-09-11T15:11:01.450 回答
1

您原来的问题与类似。

UserDao您的应用程序上下文中有两个实例- 一个在 中手动声明application-context.xml,另一个由<context:component-scan>(由于存在@Component)发现。前者有它的sessionFactory集合 (by <property>),而后者没有它 (因为它不是@Autowired)。

因此,您应该手动声明您的 bean(并删除@Component),或者允许 Spring 自动发现它(并使用 注释sessionFactory@Autowired因为在这种情况下您不手动设置它)。

No Hibernate Session bound to thread错误表示您解决了最初的问题,现在应该看看 NimChimpsky 的回答和其他有关使用@Transactional和 Spring-managed transactions的材料。

于 2012-09-11T16:07:45.937 回答