hibernate和spring结合的时候,可以直接用hibernateTemplate,也是由spring进行注入,加上代码试试:
  <bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
  </bean>

解决方案 »

  1.   

    UsersDao uu=new UsersImpl();
    你这里用new了当然没注入了。你都叫给spring管理了应该由spring来创建这个UsersDao
    UsersDao uu=(UsersDao)new ClassPathXmlApplicationContext("applicationContext.xml").getBean("userDao");
      

  2.   

    无论怎样sessionFactory都是注入不了值
      

  3.   

    我发现重复了,后来也删掉了,但还是没用。反正测试来测试去就是发现sessionFactory无法注入
      

  4.   

    2013-1-4 13:42:51 org.apache.catalina.core.AprLifecycleListener init
    信息: Loaded APR based Apache Tomcat Native library 1.1.24 using APR version 1.4.6.
    2013-1-4 13:42:51 org.apache.catalina.core.AprLifecycleListener init
    信息: APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
    2013-1-4 13:42:52 org.apache.catalina.core.AprLifecycleListener initializeSSL
    信息: OpenSSL successfully initialized (OpenSSL 1.0.1c 10 May 2012)
    2013-1-4 13:42:52 org.apache.coyote.AbstractProtocol init
    信息: Initializing ProtocolHandler ["http-apr-8080"]
    2013-1-4 13:42:52 org.apache.coyote.AbstractProtocol init
    信息: Initializing ProtocolHandler ["ajp-apr-8009"]
    2013-1-4 13:42:52 org.apache.catalina.startup.Catalina load
    信息: Initialization processed in 1233 ms
    2013-1-4 13:42:52 org.apache.catalina.core.StandardService startInternal
    信息: Starting service Catalina
    2013-1-4 13:42:52 org.apache.catalina.core.StandardEngine startInternal
    信息: Starting Servlet Engine: Apache Tomcat/7.0.32
    2013-1-4 13:42:52 org.apache.catalina.startup.HostConfig deployDirectory
    信息: Deploying web application directory C:\apache-tomcat-7.0.32\webapps\docs
    2013-1-4 13:42:52 org.apache.catalina.startup.HostConfig deployDirectory
    信息: Deploying web application directory C:\apache-tomcat-7.0.32\webapps\examples
    2013-1-4 13:42:53 org.apache.catalina.core.ApplicationContext log
    信息: ContextListener: contextInitialized()
    2013-1-4 13:42:53 org.apache.catalina.core.ApplicationContext log
    信息: SessionListener: contextInitialized()
    2013-1-4 13:42:53 org.apache.catalina.core.ApplicationContext log
    信息: ContextListener: attributeAdded('org.apache.jasper.compiler.TldLocationsCache', 'org.apache.jasper.compiler.TldLocationsCache@940b84')
    2013-1-4 13:42:53 org.apache.catalina.startup.HostConfig deployDirectory
    信息: Deploying web application directory C:\apache-tomcat-7.0.32\webapps\host-manager
    2013-1-4 13:42:53 org.apache.catalina.startup.HostConfig deployDirectory
    信息: Deploying web application directory C:\apache-tomcat-7.0.32\webapps\manager
    2013-1-4 13:42:53 org.apache.catalina.startup.HostConfig deployDirectory
    信息: Deploying web application directory C:\apache-tomcat-7.0.32\webapps\ROOT
    2013-1-4 13:42:53 org.apache.catalina.startup.HostConfig deployDirectory
    信息: Deploying web application directory C:\apache-tomcat-7.0.32\webapps\ssh_test1
    2013-1-4 13:42:57 org.apache.catalina.core.ApplicationContext log
    信息: No Spring WebApplicationInitializer types detected on classpath
    2013-1-4 13:42:57 org.apache.catalina.core.ApplicationContext log
    信息: Initializing Spring root WebApplicationContext
    2013-1-4 13:42:57 org.springframework.web.context.ContextLoader initWebApplicationContext
    信息: Root WebApplicationContext: initialization started
    2013-1-4 13:42:57 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    信息: Refreshing Root WebApplicationContext: startup date [Fri Jan 04 13:42:57 CST 2013]; root of context hierarchy
    2013-1-4 13:42:57 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    信息: Loading XML bean definitions from class path resource [applicationContext.xml]
    2013-1-4 13:42:58 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@14653a3: defining beans [dataSource,sessionFactory,hibernateTemplate,userDao,mgr,transactionManager,transactionInterceptor,proxyCreator]; root of factory hierarchy
    2013-1-4 13:42:58 com.mchange.v2.log.MLog <clinit>
    信息: MLog clients using java 1.4+ standard logging.
    2013-1-4 13:42:58 com.mchange.v2.c3p0.C3P0Registry banner
    信息: Initializing c3p0-0.9.1 [built 16-January-2007 14:46:42; debug? true; trace: 10]
    2013-1-4 13:42:59 org.hibernate.annotations.common.Version <clinit>
    INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
    2013-1-4 13:42:59 org.hibernate.Version logVersion
    INFO: HHH000412: Hibernate Core {4.1.9.Final}
    2013-1-4 13:42:59 org.hibernate.cfg.Environment <clinit>
    INFO: HHH000206: hibernate.properties not found
    2013-1-4 13:42:59 org.hibernate.cfg.Environment buildBytecodeProvider
    INFO: HHH000021: Bytecode provider name : javassist
    2013-1-4 13:42:59 org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
    WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
    2013-1-4 13:42:59 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
    信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1bquq9k8s14sgwby4xsao|ed65e0, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> oracle.jdbc.driver.OracleDriver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1bquq9k8s14sgwby4xsao|ed65e0, idleConnectionTestPeriod -> 0, initialPoolSize -> 1, jdbcUrl -> jdbc:oracle:thin:@localhost:1521:orcl, lastAcquisitionFailureDefaultUser -> null, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 20, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 1, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]
    2013-1-4 13:43:00 org.hibernate.dialect.Dialect <init>
    INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
    2013-1-4 13:43:00 org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
    INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
    2013-1-4 13:43:00 org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
    INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
    2013-1-4 13:43:00 org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
    INFO: HHH000397: Using ASTQueryTranslatorFactory
    2013-1-4 13:43:01 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    INFO: HHH000228: Running hbm2ddl schema update
    2013-1-4 13:43:01 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    INFO: HHH000102: Fetching database metadata
    2013-1-4 13:43:01 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    INFO: HHH000396: Updating schema
    2013-1-4 13:43:01 org.hibernate.tool.hbm2ddl.TableMetadata <init>
    INFO: HHH000261: Table found: SSH.USERS
    2013-1-4 13:43:01 org.hibernate.tool.hbm2ddl.TableMetadata <init>
    INFO: HHH000037: Columns: [id, birth, name, pass]
    2013-1-4 13:43:01 org.hibernate.tool.hbm2ddl.TableMetadata <init>
    INFO: HHH000108: Foreign keys: []
    2013-1-4 13:43:01 org.hibernate.tool.hbm2ddl.TableMetadata <init>
    INFO: HHH000126: Indexes: [pk_user_id]
    2013-1-4 13:43:01 org.hibernate.tool.hbm2ddl.SchemaUpdate execute
    INFO: HHH000232: Schema update complete
    2013-1-4 13:43:01 org.springframework.orm.hibernate4.HibernateTransactionManager afterPropertiesSet
    信息: Using DataSource [com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1bquq9k8s14sgwby4xsao|ed65e0, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> oracle.jdbc.driver.OracleDriver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1bquq9k8s14sgwby4xsao|ed65e0, idleConnectionTestPeriod -> 0, initialPoolSize -> 1, jdbcUrl -> jdbc:oracle:thin:@localhost:1521:orcl, lastAcquisitionFailureDefaultUser -> null, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 20, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 1, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]] of Hibernate SessionFactory for HibernateTransactionManager
    2013-1-4 13:43:01 org.springframework.web.context.ContextLoader initWebApplicationContext
    信息: Root WebApplicationContext: initialization completed in 4228 ms
      

  5.   

    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Parsing configuration file [struts-default.xml]
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Parsing configuration file [struts-plugin.xml]
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Parsing configuration file [struts.xml]
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (spring) for (com.opensymphony.xwork2.ObjectFactory)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.FileManagerFactory)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.XWorkConverter)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.TextProvider)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.LocaleProvider)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.ActionProxyFactory)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.ObjectTypeDeterminer)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (org.apache.struts2.dispatcher.mapper.ActionMapper)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (jakarta) for (org.apache.struts2.dispatcher.multipart.MultiPartRequest)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (org.apache.struts2.views.freeer.FreeerManager)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (org.apache.struts2.components.UrlRenderer)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.validator.ActionValidatorManager)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.util.ValueStackFactory)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.util.reflection.ReflectionProvider)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.util.reflection.ReflectionContextFactory)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.util.PatternMatcher)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (org.apache.struts2.dispatcher.StaticContentLoader)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.UnknownHandlerManager)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (org.apache.struts2.views.util.UrlHelper)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.CollectionConverter)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.ArrayConverter)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.DateConverter)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.NumberConverter)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Choosing bean (struts) for (com.opensymphony.xwork2.conversion.impl.StringConverter)
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Initializing Struts-Spring integration...
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Setting autowire strategy to name
    2013-1-4 13:43:02 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: ... initialized Struts-Spring integration successfully
    2013-1-4 13:43:02 org.apache.coyote.AbstractProtocol start
    信息: Starting ProtocolHandler ["http-apr-8080"]
    2013-1-4 13:43:02 org.apache.coyote.AbstractProtocol start
    信息: Starting ProtocolHandler ["ajp-apr-8009"]
    2013-1-4 13:43:02 org.apache.catalina.startup.Catalina start
    信息: Server startup in 10525 ms
      

  6.   

    你用new的方式当然不行了,你只要提供setter getter由spring注入就可以了
      

  7.   

    是UsersImpl里的getHibernateTemplate()获取不到值,不关LoginAction里的代码的事。那是为了方便测试写的,实际上自然不会那么写。
      

  8.   

     extends HibernateDaoSupport 
     HibernateDaoSupport
     这个楼主配置了吗? 
      

  9.   


    <bean id="HibernateDaoSupport" class="org.springframework.orm.hibernate3.support.HibernateDaoSupport">
           <property name="dataSource" ref="dataSource"/>
         </bean>试一试
      

  10.   

    试了下,报错很严重
    java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;应该就是 <bean id="userDao" class="test1.impl.UsersImpl">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>
    </bean>
    没起作用
      

  11.   

    是在测试类里面写的还是在启动服务后的action里面写的。你配置没有什么问题如果在启动服务后的action里面直接给setter getter就可以了,如果是不启动服务的JUnit用这种写法测试
      

  12.   

    启动服务器后的LoginAction里的:
    public String execute(){
    try {
    int userId=mgr.loginValid(name, pass);
    if(userId>0){
    ActionContext.getContext().getSession().put("userId", userId);
    return SUCCESS;
    }else{
    ActionContext.getContext().getSession().put("msg", "用户名/密码不正确");
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return "failure";
    }
    --------------------------------------
    UsersManagerImpl里的 public int loginValid(String name, String pass) throws Exception {
    System.out.println("1--->"+name);
    try {
    Users user = userDao.findByNameAndPass(name, pass);
    if (user != null) {
    return user.getId();
    }
    return -1;
    } catch (Exception e) {
    throw new Exception("验证用户名密码时出错");
    }
    }
    ------------------------------
    UsersImpl里的:
    public Users findByNameAndPass(String name, String pass) {
    System.out.println("2--->"+name);
    List<?> li=getHibernateTemplate().find("from Users where name=? and pass=?", name,pass);
    if(li!=null&&li.size()>0){
    return (Users) li.get(0);
    }
    return null;

    }
    -----------------------------------
    配置:
    <bean id="userDao" class="test1.impl.UsersImpl">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>
    </bean> <bean id="mgr" class="test1.impl.UsersManagerImpl">
    <property name="userDao">
    <ref bean="userDao" />
    </property>
    </bean>
    ---------------------------------
    运行结果:
    初始化信息:
    INFO: HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetExceptionWARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
    结果:2013-1-4 15:18:56 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: Setting autowire strategy to name
    2013-1-4 15:18:56 com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
    信息: ... initialized Struts-Spring integration successfully
    2013-1-4 15:20:16 org.apache.jasper.compiler.TldLocationsCache tldScanJar
    信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    1--->ccb
    2--->ccb
    java.lang.Exception: 验证用户名密码时出错
    at test1.impl.UsersManagerImpl.loginValid(UsersManagerImpl.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
      

  13.   

    好像注入成功了,但还是报错,这句话错了吗?
    List<?> li=getHibernateTemplate().find("from Users where name=? and pass=?", name,pass);Users是
    import java.io.Serializable;
    import java.util.Date;public class Users implements Serializable {
    private static final long serialVersionUID = -3990542857351264227L;
    private int id=-1;
    private String name=null;
    private String pass=null;
    private Date birth=null;

    public Users() {
    super();
    }
    。。-----------------------------
    Users.hbm.xml是
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="test1.po">   
        <class name="Users" table="users" schema="ssh">
            <id name="id" column="id">
              <generator class="sequence"></generator>
            </id>
            <property name="name" column="name"></property>
            <property name="pass" column="pass"></property>
            <property name="birth" column="birth"></property>
        </class>
    </hibernate-mapping>
      

  14.   

    突然间发现代码有几处地方错了,改正后新错误信息变为hibernate4和hibernate3不能混用,因为hibernateDaoSupport只有hibernate3有,4没有。后来换为hibernate3,能正确出结果了。
    只是hibernate4既然出了,难道就不能用吗?
      

  15.   

    hibernate4不再支持HibernateDaoSupport这个类了,需要使用session来完成增删改查。
    获取session的方法:
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
    return sessionFactory;
    }
    @Resource
    public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
    }
    private Session getCurrentSession(){
    return this.sessionFactory.getCurrentSession();
    }
    如果要添加对象,就使用:
    @Override
    public void add(User user) {
    this.getCurrentSession().save(user);
    }