我的hibernate和spring 整合时getHibernateTemplate().find出现空指针问题

Spring组件: class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- 数据库连接参数信息 -->

方言,映射描述都没问题,
/context:component-scan

<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 定义通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
    <!-- 指定目标组件中的哪些方法采用哪种事务管理方式 -->
    <tx:attributes>
        <tx:method name="find*" read-only="true"  propagation="REQUIRED"/>
        <tx:method name="get*" read-only="true"     propagation="REQUIRED"/>
        <tx:method name="save*" propagation="REQUIRED"/>
        <tx:method name="update*" propagation="REQUIRED"/>
        <tx:method name="delete*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>
<!-- AOP配置,将通知和切入结合(目标对象) -->
<aop:config>
    <!-- 将所有DAO作目标 -->
    <aop:pointcut expression="within(org.dao..*)" 
<bean id="txManager" 
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory">
    </property>
</bean>
<!-- 开启事务注解配置 -->
<tx:annotation-driven transaction-manager="txManager"/>
suannai0314
鹳狸媛 楼主的这个问题解决了么?下边的答案能解决问题么?如果可以麻烦点击答案旁的√采纳哦~如果没有也可以将自己的答案贴上然后进行采纳的。
6 年多之前 回复

4个回答

三张表:




UserInfo_SEQ







    <property name="grade" type="integer">
        <column name="GRADE"  />
    </property>
    <property name="Content" type="string">
        <column name="CONTENT"  />
    </property>
    <property name="createDate" type="date">
        <column name="CREATEDATE"  />
    </property>
    <property name="userId" type="integer"  update="false"
                      insert="false" >
        <column name="USERID"  />
    </property>
    <property name="flag" type="integer">
        <column name="FLAG"  />
    </property>
    <!-- 指定userInfo属性,采用many-to-one关系加载 -->
    <many-to-one name="userInfo" column="USERID"  lazy="false"
        class="org.entity.UserInfo">
    </many-to-one>
    <!-- 采用一(EventGrade)对多(Event)加载信息 -->
  <set name="event_Grades" >
        <key column="GRADE"></key>
        <one-to-many 
            class="org.entity.Event_Grade"/>
    </set>

table="EVENT_GRADE">



UserInfo_SEQ







</class>





UserInfo_SEQ







</class>





UserInfo_SEQ







    <property name="userName" type="string">
        <column name="USERNAME"  />
    </property>
     <!-- 采用一对多关系加载相关的Service记录 -->
  <set name="events" inverse="true" cascade="all">
        <!-- 指定关联条件字段,写外键字段 -->
        <key column="USERID"></key>
        <!-- 指定要采用的关系,要加载的数据类型 -->
        <one-to-many class="org.entity.Event"/>
  </set>
</class>

table="EVENT_GRADE">



UserInfo_SEQ







public Event findById(Integer id)throws DAOException{

// String findAllById = "from Event where id = ?";
// Object[] primes = {id};
List list = (List)this.getHibernateTemplate().find("from Event where id ="+id );
if(list!=null && !list.isEmpty()){
return list.get(0);
}
// Event event = (Event)this.getHibernateTemplate().get(Event.class,id);
// return event;
return null;

}

public List findGrade() throws DAOException {
String findGradeName = "select gradeName from Event_Grade ";
List names= new ArrayList();
System.out.println( this.getHibernateTemplate().find( findGradeName));
names.addAll( this.getHibernateTemplate().find(findGradeName));
if(!names.isEmpty()){
for (Object o : names) {
System.out.println(o);
}
return names;
}else {
System.out.println("DAOImpl为空");
return null;
}
}
测试返回的结果都为null,请哪位大神给解决一下,谢谢了

把错误信息贴出来塞。。。。。。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Hibernate 和spring 整合
在spring和Hibernate做整合的时候 import org.springframework.orm.hibernate3.support.HibernateDaoSupport类中的这个方法getHibernateTemplate().findById(Integer id);"getHibernateTemplate()"这个方法是怎么获得数据源,HibernateDaoSupport这个类又是spring中的 晕; 我要只用spring一个框架 用HibernateDaoSupport.findById();可以获取到数据吗; 那数据源在application.xml中配置后, 还要进行其他什么配置呢? 这个问题好纠结啊。 这个类HibernateDaoSuppor和hibernate框架有什么关系? 整合后觉得spring 和 hibernate 没有什么关系啊!!!
dwr和spring整合时出的问题
dwr和spring整合时出了的一点问题,请问有谁知道这是怎么回事呢? 具体代码如下: dwr.xml [code="java"] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd"> <dwr> <allow> <create creator="spring" javascript="ItemDAO"> <param name="beanName" value="itemDAO"></param> <param name="location" value="applicationContext.xml" /> </create> <convert converter="bean" match="com.Item.wise.DBItem"> <param name="include" value="id,name,order,parent,subItem,url" /> </convert> </allow> </dwr> [/code] ItemDAO.java [code="java"] public class ItemDAO extends HibernateDaoSupport{ public List<DBItem> findItems(String parent) { List<DBItem> list = this.getHibernateTemplate().find("from DBItem where parent="+parent); return list; } } [/code] applicationContext.xml [code="java"] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://127.0.0.1:3306/lin?useUnicode=true&amp;characterEncoding=UTF-8"> </property> <property name="username" value="root"></property> <property name="password" value="lin"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>com/Item/wise/DBItem.hbm.xml</value> </list> </property> </bean> <bean id="itemDAO" class="com.Item.wise.ItemDAO"> <property name="sessionFactory"> <ref local="sessionFactory" /> </property> </bean> </beans> [/code] [code] 2009-5-22 13:36:49 org.directwebremoting.impl.StartupUtil logStartup 信息: Starting: DwrServlet v3.0.0.116.rc1 on Apache Tomcat/6.0.16 / JDK 1.6.0_06 from Sun Microsystems Inc. at /AjaxStudy 2009-5-22 13:36:50 org.directwebremoting.impl.DTDEntityResolver resolveEntity 警告: Deprecated public id in dwr.xml. Use: <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr//dwr30.dtd"> 2009-5-22 13:36:50 org.directwebremoting.util.LocalUtil setParams 警告: No property 'location' on org.directwebremoting.spring.SpringCreator 2009-5-22 13:36:50 org.directwebremoting.spring.SpringCreator getBeanFactory 信息: Spring BeanFactory via ClassPathXmlApplicationContext using 1configLocations. 2009-5-22 13:36:51 org.springframework.core.CollectionFactory <clinit> 信息: JDK 1.4+ collections available 2009-5-22 13:36:51 org.springframework.core.CollectionFactory <clinit> 信息: Commons Collections 3.x available 2009-5-22 13:36:51 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [applicationContext.xml] 2009-5-22 13:36:51 org.directwebremoting.impl.DefaultCreatorManager addCreator 严重: Error loading class for creator 'SpringCreator[ItemDAO]'. java.lang.NullPointerException at org.directwebremoting.spring.SpringCreator.getInstance(SpringCreator.java:153) at org.directwebremoting.spring.SpringCreator.getType(SpringCreator.java:107) at org.directwebremoting.impl.DefaultCreatorManager.addCreator(DefaultCreatorManager.java:97) at org.directwebremoting.impl.DefaultCreatorManager.addCreator(DefaultCreatorManager.java:78) at org.directwebremoting.impl.DwrXmlConfigurator.loadCreate(DwrXmlConfigurator.java:268) at org.directwebremoting.impl.DwrXmlConfigurator.loadAllows(DwrXmlConfigurator.java:218) at org.directwebremoting.impl.DwrXmlConfigurator.configure(DwrXmlConfigurator.java:164) at org.directwebremoting.impl.StartupUtil.configureFromDefaultDwrXml(StartupUtil.java:587) at org.directwebremoting.impl.StartupUtil.configureContainerFully(StartupUtil.java:696) at org.directwebremoting.servlet.DwrServlet.configureContainer(DwrServlet.java:109) at org.directwebremoting.servlet.DwrServlet.init(DwrServlet.java:68) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:806) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:129) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) 2009-5-22 13:36:51 org.directwebremoting.impl.DefaultCreatorManager getCreator 严重: Class not found: 'ItemDAO' 2009-5-22 13:36:51 org.directwebremoting.impl.DefaultCreatorManager getCreator 警告: Names of known classes are: __Data Demo JavaDate __System 2009-5-22 13:36:51 org.directwebremoting.servlet.ExceptionHandler handle 警告: Error: java.lang.SecurityException: Class not found [/code] [b]问题补充:[/b] web.xml [code="java"] <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> [/code] [b]问题补充:[/b] Item.jsp [code="java"] <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"/> <title>DWR - Test Home</title> <script type='text/javascript' src='dwr/interface/ItemDAO.js'></script> <script type='text/javascript' src='dwr/engine.js'></script> <script type='text/javascript' src='dwr/util.js'></script> <script> function load() { ItemDAO.findItems(0,createTable); } function createTable(data) { DWRUtil.removeAllRows("itemTable"); DWRUtil.addRows("itemTable", data, cellFunctions); } var cellFunctions = [ function(data){ return data.name; }, function(data) { return data.url; }, function(data) { return data.order; }, function(data) { btn.innerHTML = "<a href='"+data.url+"'>a</a>"; } ]; </script> </head> <body onload="load()"> <table id="itemTable"> <thead> <tr><th>Name</th><th>url</th><th>order</th><th>operation</th> </thead> </table> </body> </html> [/code] 谢谢studying_ 的耐心。
hibernate DAO中关于session的管理
最近在整理hibernate的性能优化时,碰到了session的问题。 有几个问题不解,想在此请教一下各位高手们。 1、hibernate官网中介绍了一种threadlocal模式对session进行管理,本人也在filter中设置了这种功能,的确自己创建的session确实达到了与线程绑定的功能,但是对于DAO这一层(与SPRING整合)在使用getHibernateTemplate的回调函数中的session却无法达到该目的,也即getHibernateTemplate每次都创建了一个新的session,具体代码如下: fruitDAO.getHibernateTemplate().execute(new HibernateCallback(){ public Object doInHibernate(Session session){ System.out.println(session.hashCode()); return null; } }); 每次打出来的hashCode都不一样。 2、hibernate对于频繁创建关闭session的代价到底有多少,在系统中配置了连接池,session在关闭时是否对hibernate的数据库连接有影响。 谢谢各位了。
spring mvc 整合hibernate 菜鸟级问题
小弟想用spring mvc 整合hibernate 但是spring总是如法注入。 spring配置文件如下 [code="java"] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="jdbcPropertyConfiger" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass"> <value>${datasource.driverClassName}</value> </property> <property name="jdbcUrl"> <value>${datasource.url}</value> </property> <property name="user"> <value>${datasource.username}</value> </property> <property name="password"> <value>${datasource.password}</value> </property> <property name="acquireIncrement"> <value>${c3p0.acquireIncrement}</value> </property> <property name="initialPoolSize"> <value>${c3p0.initialPoolSize}</value> </property> <property name="minPoolSize"> <value>${c3p0.minPoolSize}</value> </property> <property name="maxPoolSize"> <value>${c3p0.maxPoolSize}</value> </property> <property name="maxIdleTime"> <value>${c3p0.maxIdleTime}</value> </property> <property name="idleConnectionTestPeriod"> <value>${c3p0.idleConnectionTestPeriod}</value> </property> <property name="maxStatements"> <value>${c3p0.maxStatements}</value> </property> <property name="numHelperThreads"> <value>${c3p0.numHelperThreads}</value> </property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource" /> </property> </bean> <bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager" ref="transactionManager"></property> <property name="transactionAttributes"> <props> <prop key="query*">PROPAGATION_REQUIRED,readOnly</prop> <prop key="save*">PROPAGATION_REQUIRED</prop> <prop key="delete*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> </props> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mappingResources"> <list> <value>classpath:ac02.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> </props> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="QscDBService" class ="com.qsc.m.QscDBServiceImpl"> <property name="sessionFactory" ref="sessionFactory" /> <property name="hibernateTemplate" ref="hibernateTemplate" /> </bean> <bean id="ControllerJoin" class="com.qsc.c.ControllerJoin"> <property name="QscDBService" ref="QscDBService"></property> </bean> </beans> [/code] QscDBservice类如下 [code="java"] package com.qsc.m; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.orm.hibernate3.HibernateTemplate; import com.qsc.pojo.ac02; public class QscDBServiceImpl extends JdbcTemplate implements QscDBService { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public void sava(ac02 ac02) { hibernateTemplate.save(ac02); } [/code] ControllerJoin类如下 [code="java"] package com.qsc.c; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import com.qsc.m.QscDBService; import com.qsc.pojo.ac02; import com.qsc.spring.ContextLoaderListener; public class ControllerJoin implements Controller { private QscDBService qsc; public QscDBService getQsc() { return qsc; } public void setQsc(QscDBService qsc) { this.qsc = qsc; } public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { //final QscDBService qsc = (QscDBService)ContextLoaderListener.getBean("QscDBService"); ac02 ac02 = new ac02(); String aac001 = arg0.getParameter("account"); String aac002 = arg0.getParameter("name"); String aac003 = arg0.getParameter("age"); String aac004 = arg0.getParameter("email"); String aac005 = arg0.getParameter("phone"); String aac006 = arg0.getParameter("pass"); ac02.setAac001(aac001); ac02.setAac002(aac002); ac02.setAac003(Integer.parseInt(aac003)); ac02.setAac004(aac004); ac02.setAac005(aac005); ac02.setAac006(aac006); qsc.sava(ac02); return new ModelAndView("success"); } } [/code] debug后发现 qsc和hibernatetemplate 这两个全是null 说明spring没注入成功,这是为啥啊? 谢谢
struts2+spring2.5+hibernate整合的问题
<p>ssh整合的时候不报错,但插入的时候数据库也没有数据,控制台把insert语句已经打出来了,这是什么情况,请大侠们帮忙看看 <br><br><br>applicationContext.xml 配置如下:</p> <p> </p> <p>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;beans xmlns="<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a>"<br>xmlns:context="<a href="http://www.springframework.org/schema/context">http://www.springframework.org/schema/context</a>"<br>xmlns:tx="<a href="http://www.springframework.org/schema/tx">http://www.springframework.org/schema/tx</a>"<br>xmlns:aop="<a href="http://www.springframework.org/schema/aop">http://www.springframework.org/schema/aop</a>"<br> xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>"<br> xsi:schemaLocation="<a href="http://www.springframework.org/schema/beans">http://www.springframework.org/schema/beans</a><br><a href="http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">http://www.springframework.org/schema/beans/spring-beans-2.5.xsd</a><br><a href="http://www.springframework.org/schema/tx">http://www.springframework.org/schema/tx</a><br><a href="http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">http://www.springframework.org/schema/tx/spring-tx-2.5.xsd</a><br><a href="http://www.springframework.org/schema/aop">http://www.springframework.org/schema/aop</a><br><a href="http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">http://www.springframework.org/schema/aop/spring-aop-2.5.xsd</a><br><a href="http://www.springframework.org/schema/context">http://www.springframework.org/schema/context</a><br><a href="http://www.springframework.org/schema/context/spring-context-2.5.xsd">http://www.springframework.org/schema/context/spring-context-2.5.xsd</a><br>" default-autowire="byName" default-lazy-init="true"&gt;</p> <p> &lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;<br>  &lt;property name="locations"&gt;<br>   &lt;list&gt;<br>    &lt;value&gt;classpath*:jdbc.properties&lt;/value&gt;<br>   &lt;/list&gt;<br>  &lt;/property&gt;<br> &lt;/bean&gt;<br> <br> &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt;<br>  &lt;property name="driverClassName" value="${jdbc.driver}"/&gt;<br>  &lt;property name="url" value="${jdbc.url}"/&gt;<br>  &lt;property name="username" value="${jdbc.username}"/&gt;<br>  &lt;property name="password" value="${jdbc.password}"&gt;&lt;/property&gt;<br>  <br>  &lt;property name="initialSize" value="5" /&gt;<br>  &lt;property name="maxActive" value="100" /&gt;<br>  &lt;property name="maxIdle" value="30" /&gt;<br>  &lt;property name="maxWait" value="500" /&gt;<br>  &lt;property name="poolPreparedStatements" value="false" /&gt;<br>  &lt;property name="defaultAutoCommit" value="false" /&gt;<br> &lt;/bean&gt;<br> <br> &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt;<br>     &lt;property name="dataSource" ref="dataSource"/&gt;<br>     &lt;property name="mappingResources"&gt;<br>       &lt;list&gt;<br>         &lt;value&gt;com/demo/mapping/demo.hbm.xml&lt;/value&gt;<br>       &lt;/list&gt;<br>     &lt;/property&gt;<br>  &lt;property name="hibernateProperties"&gt;<br>   &lt;props&gt;<br>    &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.OracleDialect&lt;/prop&gt;<br>       &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;<br>   &lt;/props&gt;<br>  &lt;/property&gt;<br>  <br> &lt;/bean&gt;<br> <br> &lt;bean id="dDao" class="com.demo.dao.Impl.demoDaoImpl"&gt;<br>  &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt;<br> &lt;/bean&gt;<br> <br> &lt;bean id="dService" class="com.demo.service.Impl.demoServiceImpl"&gt;<br>  &lt;property name="dDao" ref="dDao"&gt;&lt;/property&gt;<br> &lt;/bean&gt;<br> &lt;bean id="txManage" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt;  <br>     &lt;property name="sessionFactory" ref="sessionFactory"/&gt;  <br> &lt;/bean&gt;  </p> <p>&lt;/beans&gt;</p> <p> </p> <p>struts.xml 如下:</p> <p> </p> <p>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;<br>&lt;!DOCTYPE struts PUBLIC<br>    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"<br>    "<a href="http://struts.apache.org/dtds/struts-2.1.7.dtd">http://struts.apache.org/dtds/struts-2.1.7.dtd</a>"&gt;<br>&lt;struts&gt;<br> &lt;package name="demo" namespace="/demo" extends="struts-default"&gt;<br>  &lt;action name="demo" class="com.demo.action.RegisterAction"&gt;<br>   &lt;result name="index"&gt;/demo/demo-index.jsp&lt;/result&gt;<br>   &lt;result name="add"&gt;/demo/demo-add.jsp&lt;/result&gt;<br>   &lt;result name="operate"&gt;/demo/demo-add.jsp&lt;/result&gt;<br>   &lt;result name="save" type="redirectAction"&gt;demo!index.action&lt;/result&gt;<br>   &lt;result name="update" type="redirectAction"&gt;demo!index.action&lt;/result&gt;<br>   &lt;result name="delete" type="redirectAction"&gt;demo!index.action&lt;/result&gt;<br>  &lt;/action&gt;<br> &lt;/package&gt;<br>&lt;/struts&gt;</p> <p> </p> <p>jdbc.properties  如下:</p> <p> </p> <p>jdbc.driver=oracle.jdbc.driver.OracleDriver<br>jdbc.url=jdbc:oracle:thin:@192.168.6.90:1521:orcl<br>jdbc.username=example<br>jdbc.password=123456<br>hibernate.dialect=org.hibernate.dialect.Oracle10gDialect</p> <p> </p> <p>web.xml   如下:</p> <p>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;web-app version="2.5" xmlns="<a href="http://java.sun.com/xml/ns/javaee">http://java.sun.com/xml/ns/javaee</a>"<br> xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>"<br> xsi:schemaLocation="<a href="http://java.sun.com/xml/ns/javaee">http://java.sun.com/xml/ns/javaee</a> <br> <a href="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd</a>"&gt;<br> <br>    &lt;context-param&gt;<br>   &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;<br>   &lt;param-value&gt;classpath:applicationContext.xml&lt;/param-value&gt;<br>    &lt;/context-param&gt;<br>  &lt;listener&gt;<br>      &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;<br>     &lt;/listener&gt;<br>  &lt;filter&gt;<br>   &lt;filter-name&gt;struts2Filter&lt;/filter-name&gt;<br>   &lt;filter-class&gt;org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter&lt;/filter-class&gt;<br>  &lt;/filter&gt;<br>  &lt;filter-mapping&gt;<br>   &lt;filter-name&gt;struts2Filter&lt;/filter-name&gt;<br>   &lt;url-pattern&gt;/*&lt;/url-pattern&gt;<br>  &lt;/filter-mapping&gt;<br>&lt;/web-app&gt;<br> </p> <p>dao  接口如下:</p> <p>package com.demo.dao;</p> <p>import java.io.Serializable;<br>import java.util.List;</p> <p>import com.demo.model.Demo;</p> <p>public interface demoDao {<br> <br> public void save(Demo demo);</p> <p> public List&lt;Demo&gt; getDemos(final String strHql,final Object...params);<br> <br> public List&lt;Demo&gt; getDemos();<br> <br> public void delete(Demo demo);<br> <br> public abstract &lt;T&gt; T findByPrimaryKey(Class&lt;T&gt; class1, Serializable serializable);<br> <br> public void update(Demo demo);<br>}</p> <p>dao的实现:</p> <p>package com.demo.dao.Impl;</p> <p>import java.io.Serializable;<br>import java.sql.SQLException;<br>import java.util.ArrayList;<br>import java.util.List;</p> <p>import org.hibernate.HibernateException;<br>import org.hibernate.Query;<br>import org.hibernate.Session;<br>import org.springframework.orm.hibernate3.HibernateCallback;<br>import org.springframework.orm.hibernate3.HibernateTemplate;<br>import org.springframework.orm.hibernate3.support.HibernateDaoSupport;<br>import org.springframework.transaction.annotation.Transactional;</p> <p>import com.demo.dao.demoDao;<br>import com.demo.model.Demo;</p> <p>public class demoDaoImpl  extends HibernateDaoSupport implements demoDao{</p> <p> @Transactional<br> public void save(Demo demo) {<br>  this.getHibernateTemplate().save(demo);<br> }</p> <p> @SuppressWarnings("unchecked")<br> public List&lt;Demo&gt; getDemos(final String strHql,final Object...params) {<br>  List&lt;Demo&gt; demos=new ArrayList&lt;Demo&gt;();<br>  demos=this.getHibernateTemplate().executeFind(new HibernateCallback() {<br>     public Object doInHibernate(Session session) throws HibernateException,SQLException {<br>      Query query=session.createQuery(strHql);<br>      for(int i=0;params!=null&amp;&amp;i&lt;params.length;i++){<br>       query.setString(i,params[i].toString());<br>      }<br>      return query.list();<br>   }<br>  });<br>  return demos;<br> }</p> <p> public void delete(Demo demo) {<br>  this.getHibernateTemplate().delete(demo);<br> }</p> <p>  @SuppressWarnings("unchecked")<br>  public &lt;T&gt; T findByPrimaryKey(Class&lt;T&gt; clazz, Serializable key) {<br>         T obj = (T) getSession().get(clazz, key);<br>         return obj;<br>     }</p> <p> public void update(Demo demo) {<br>  this.getHibernateTemplate().update(demo);<br> }</p> <p>  @SuppressWarnings("unchecked")<br> public List&lt;Demo&gt; getDemos() {<br>  return this.getHibernateTemplate().find("from Demo where 1=1");<br> }</p> <p> <br>}</p> <p>service接口:</p> <p>package com.demo.service;</p> <p>import java.io.Serializable;<br>import java.util.List;</p> <p>import com.demo.model.Demo;</p> <p>public interface demoService {<br> <br> public void save(Demo demo);<br> <br> public List&lt;Demo&gt; getDemos(final String strHql,final Object...params);<br> <br> public List&lt;Demo&gt; getDemos();<br> <br> public void delete(Demo demo);<br> <br> public &lt;T&gt; T findByPrimaryKey(Class&lt;T&gt; class1, Serializable serializable);<br> <br> public String createHql(Demo demo);<br> <br> public void update(Demo demo);<br>}</p> <p>service 的实现:</p> <p>package com.demo.service.Impl;</p> <p>import java.io.Serializable;<br>import java.util.List;</p> <p>import org.springframework.transaction.annotation.Transactional;</p> <p>import com.demo.dao.demoDao;<br>import com.demo.model.Demo;<br>import com.demo.service.demoService;</p> <p>public class demoServiceImpl implements demoService{</p> <p> private demoDao dDao;</p> <p> public demoDao getdDao() {<br>  return dDao;<br> }</p> <p> public void setdDao(demoDao dDao) {<br>  this.dDao = dDao;<br> }</p> <p> public void save(Demo demo) {<br>  dDao.save(demo);<br> }</p> <p> public List&lt;Demo&gt; getDemos(final String strHql,final Object...params) {<br>  return dDao.getDemos(strHql, params);<br> }</p> <p> public void delete(Demo demo) {<br>  dDao.delete(demo);<br> }</p> <p> @Override<br> public String createHql(Demo demo) {<br>  StringBuffer buf=new StringBuffer();<br>  buf.append("from Demo d where 1=1");<br>  if(demo!=null){<br>   buf.append("and d.name like '%"+demo.getName()+"%'");<br>  }<br>  return buf.toString();<br> }</p> <p> @Override<br> public &lt;T&gt; T findByPrimaryKey(Class&lt;T&gt; class1, Serializable serializable) {<br>  return dDao.findByPrimaryKey(class1, serializable);<br> }</p> <p> @Override<br> public void update(Demo demo) {<br>  dDao.update(demo);<br> }</p> <p> @Override<br> public List&lt;Demo&gt; getDemos() {<br>  return dDao.getDemos();<br> }<br>}<br><br>action 如下:</p> <p> </p> <p>package com.demo.action;</p> <p><br>import java.util.List;</p> <p>import com.demo.model.Demo;<br>import com.demo.service.demoService;</p> <p>public class RegisterAction {</p> <p> private Demo demo;<br> private demoService dService;<br> private List&lt;Demo&gt; demos;<br> <br> public Demo getDemo() {<br>  return demo;<br> }<br> public void setDemo(Demo demo) {<br>  this.demo = demo;<br> }<br> public demoService getdService() {<br>  return dService;<br> }<br> public void setdService(demoService dService) {<br>  this.dService = dService;<br> }<br> public List&lt;Demo&gt; getDemos() {<br>  return demos;<br> }</p> <p> public void setDemos(List&lt;Demo&gt; demos) {<br>  this.demos = demos;<br> }<br> <br> public String execute(){<br>  return "index";<br> }</p> <p> public String index(){<br>  //demos=dService.getDemos(dService.createHql(demo),null);<br>  demos=dService.getDemos();<br>  return "index";<br> }<br> public String add(){<br>  return "add";<br> }<br> public String operate(){<br>  demo=dService.findByPrimaryKey(Demo.class,demo.getId());<br>  return "operate";<br> }<br> public String save(){<br>  dService.save(demo);<br>  return "save";<br> }<br> public String delete(){<br>  demo=dService.findByPrimaryKey(Demo.class,demo.getId());<br>  dService.delete(demo);<br>  return "delete";<br> }<br> public String update(){<br>  demo=dService.findByPrimaryKey(Demo.class,demo.getId());<br>  demo.setName(demo.getName());<br>  demo.setAge(demo.getAge());<br>  demo.setAddress(demo.getAddress());<br>  dService.update(demo);<br>  return "update";<br> }<br>}</p> <p> 实体:</p> <p>package com.demo.model;</p> <p>public class Demo {</p> <p> private Long id;<br> private String name;<br> private Integer age;<br> private String address;<br> <br> public Long getId() {<br>  return id;<br> }<br> public void setId(Long id) {<br>  this.id = id;<br> }<br> public String getName() {<br>  return name;<br> }<br> public void setName(String name) {<br>  this.name = name;<br> }<br> public Integer getAge() {<br>  return age;<br> }<br> public void setAge(Integer age) {<br>  this.age = age;<br> }<br> public String getAddress() {<br>  return address;<br> }<br> public void setAddress(String address) {<br>  this.address = address;<br> }<br>}</p> <p>映射文件:demo.hbm.xml</p> <p>&lt;?xml version="1.0" encoding="utf-8"?&gt;<br>&lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"<br>"<a href="http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd</a>"&gt;<br>&lt;!-- <br>    Mapping file autogenerated by MyEclipse Persistence Tools<br>--&gt;<br>&lt;hibernate-mapping package="com.demo.model"&gt;<br>    &lt;class name="Demo" table="tb_demo" catalog="example"&gt;<br>        &lt;id name="id" type="java.lang.Long"&gt;<br>            &lt;column name="id" /&gt;<br>            &lt;generator class="sequence"&gt;<br>             &lt;param name="sequence"&gt;seq_demo&lt;/param&gt;<br>            &lt;/generator&gt;<br>        &lt;/id&gt;<br>        &lt;property name="name" type="java.lang.String"&gt;<br>            &lt;column name="tb_name" length="50" not-null="true" unique="true" /&gt;<br>        &lt;/property&gt;<br>        &lt;property name="age" type="java.lang.Integer"&gt;<br>            &lt;column name="tb_age" /&gt;<br>        &lt;/property&gt;<br>        &lt;property name="address" type="java.lang.String"&gt;<br>            &lt;column name="tb_address" length="50" not-null="true" /&gt;<br>        &lt;/property&gt;<br>    &lt;/class&gt;<br>&lt;/hibernate-mapping&gt;</p> <p> </p> <p>页面:</p> <p>demo-add.jsp  如下 :</p> <p>&lt;%@ page pageEncoding="utf-8" contentType="text/html; charset=utf-8"%&gt;<br>&lt;%@ taglib uri="/struts-tags" prefix="s"%&gt;<br>&lt;html&gt;<br> &lt;head&gt;<br>  &lt;title&gt;ssh整合测试&lt;/title&gt;<br>  &lt;script type="text/javascript" src="/SSH1/js/jquery.js"&gt;&lt;/script&gt;<br> &lt;/head&gt;<br> &lt;body&gt;<br>  &lt;form method="post" action="demo/demo.action"&gt;<br>  &lt;input type="hidden" id="num" name="demo.id" value="${demo.id}"/&gt;<br>   &lt;table&gt;<br>    &lt;tr&gt;ssh整合数据测试&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td align="right"&gt;姓名:&lt;/td&gt;&lt;td align="left"&gt;&lt;input type="text" name="demo.name" value="${demo.name}"/&gt;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td align="right"&gt;年龄:&lt;/td&gt;&lt;td align="left"&gt;&lt;input type="text" name="demo.age" value="${demo.age}"/&gt;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td align="right"&gt;家庭住址:&lt;/td&gt;&lt;td align="left"&gt;&lt;input type="text" name="demo.address" value="${demo.address}"/&gt;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td colspan="2"&gt;&lt;input type="button" value="保存" id="save"/&gt;&lt;input type="reset" value="重置"/&gt;&lt;/td&gt;&lt;/tr&gt;<br>   &lt;/table&gt;<br>  &lt;/form&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;<br>&lt;script&gt;<br> $("document").ready(function (){<br>  $("#save").click(function(){<br>   if($("#num").val()==null||$("#num").val()==""){<br>    document.forms[0].action="/SSH1/demo/demo!save.action";<br>    document.forms[0].submit();<br>   }else{<br>    alert("eee");<br>    document.forms[0].action="/SSH1/demo/demo!update.action";<br>    document.forms[0].submit();<br>   }<br>  });<br> });<br>&lt;/script&gt;</p> <p> </p> <p>demo-index.jsp  如下:</p> <p>&lt;%@ page pageEncoding="utf-8" contentType="text/html; charset=utf-8"%&gt;<br>&lt;%@ taglib uri="/struts-tags" prefix="s"%&gt;<br>&lt;html&gt;<br> &lt;head&gt;<br>  &lt;title&gt;ssh整合测试&lt;/title&gt;<br> &lt;/head&gt;<br> &lt;body&gt;<br>  &lt;form action="demo/demo.action"&gt;<br>   &lt;table&gt;<br>    &lt;tr&gt;&lt;td&gt;&lt;a href="&lt;%=request.getContextPath() %&gt;/demo/demo!add.action"&gt;添加&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;<br>    &lt;tr&gt;&lt;td&gt;序号&lt;/td&gt;&lt;td&gt;姓名&lt;/td&gt;&lt;td&gt;年龄&lt;/td&gt;&lt;td&gt;地址&lt;/td&gt;&lt;td&gt;操作&lt;/td&gt;&lt;/tr&gt;<br>    &lt;s:if test="demos.size()&gt;0"&gt;<br>     &lt;s:iterator value="demos" status="st"&gt;<br>      &lt;tr&gt;<br>       &lt;td&gt;${st.index+1}&lt;/td&gt;<br>       &lt;td&gt;${name}&lt;/td&gt;<br>       &lt;td&gt;${age}&lt;/td&gt;<br>       &lt;td&gt;${address}&lt;/td&gt;<br>       &lt;td&gt;&lt;a href="&lt;%=request.getContextPath() %&gt;/demo/demo!operate.action?demo.id=${id}"&gt;修改&lt;/a&gt;&amp;nbsp;&amp;nbsp;&lt;a href="&lt;%=request.getContextPath() %&gt;/demo/demo!operate.action?demo.id=${id}"&gt;删除&lt;/a&gt;&lt;/td&gt;<br>      &lt;/tr&gt;<br>     &lt;/s:iterator&gt;<br>    &lt;/s:if&gt;<br>   &lt;/table&gt;<br>  &lt;/form&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;</p>
getHibernateTemplate方法错误
整合spring+hibernate+struts之后, 报错如下所示。 ![图片说明](https://img-ask.csdn.net/upload/201612/10/1481299618_861636.png) 搞了好长时间了,求大神不啬吝教。谢谢,谢谢了
SSH整合,hibernate注解配置,无hbm.xml,映射出现问题
java实体类代码: ``` package cn.com.car.base.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="T_CAR") public class Car implements Serializable{ private static final long serialVersionUID = 1L; @GenericGenerator(name = "generator", strategy = "guid") @Id @GeneratedValue(generator = "generator") @Column(name = "id", unique = true, nullable = false, length = 38) private String id; @Column(name="models") private String models;//具体车型 @Column(name="type") private String type;//所属类别 @Column(name="price") private int price;//价格 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getModels() { return models; } public void setModels(String models) { this.models = models; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Car [id=" + id + ", models=" + models + ", type=" + type + ", price=" + price + "]"; } } ``` ------------------------------------------ application.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd" default-autowire="byName" default-lazy-init="true"> <!-- 属性文件读入 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:hibernate.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${hibernate.connection.driverClassName}"/> <property name="url" value="${hibernate.connection.url}"/> <property name="username" value="${hibernate.connection.username}"/> <property name="password" value="${hibernate.connection.password}"/> </bean> <!--Hibernate SessionFatory--> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="annotatedClasses"> <list> <value>cn.com.car.base.entity.Car</value> </list> </property> <property name="hibernateProperties"> <value>classpath:hibernate.properties</value> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> </beans> ``` ---------------------------------------- hibernate.properties配置文件 ``` hibernate.show_sql=true hibernate.format_sql=false hibernate.cache=org.hibernate.cache.EhCacheProvider hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.connection.driverClassName=com.mysql.jdbc.Driver hibernate.connection.url=jdbc:mysql://localhost:3306/car hibernate.connection.username=car hibernate.connection.password=123456 hibernate.c3p0.minPoolSize=5 hibernate.c3p0.maxPoolSize=50 hibernate.c3p0.timeout=1800 hibernate.c3p0.max_statement=200 ``` ---------------------------------- DAO层 ``` package cn.com.car.base.dao.impl; import java.util.HashMap; import java.util.List; import org.hibernate.Query; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import cn.com.car.base.dao.CarDao; import cn.com.car.base.entity.Car; public class CarDaoImpl extends HibernateDaoSupport implements CarDao { @Override public List<Car> getAllCar() { String sql="from T_CAR where 1=1"; List<Car> list=this.getHibernateTemplate().find(sql); return list; } @Override public List<Car> getCarByParam(HashMap<String, String> param) { StringBuilder sql=new StringBuilder(); sql.append("select * from T_CAR where 1=1"); if(param!=null){ if(param.get("type")!=null){ String type=param.get("type"); sql.append("and type="+type); } if(param.get("price")!=null){ String price=param.get("price"); sql.append("and price="+price); } Query query = this.getSession().createSQLQuery(sql.toString()); List<Car> list=query.list(); return list; } List<Car> list=this.getHibernateTemplate().find(sql.toString()); return list; } @Override public Car getCarByModels(String models) { String hql = "from T_CAR t where 1=1 " +" and t.models=? "; Query query = this.getSession().createQuery(hql).setString(0, models); return (Car) query.list().get(0); } @Override public Car getCarById(String id) { String hql = "from T_CAR t where 1=1 " +" and t.id=? "; Query query = this.getSession().createQuery(hql).setString(0, id); return (Car) query.list().get(0); } } ``` 我是模仿别的项目搭建的,没有.hbm.xml,现在运行DAO层就出现 “org.hibernate.hql.ast.QuerySyntaxException: T_CAR is not mapped [from T_CAR where 1=1]”这样的错误。
ssh整合getHibernateTemplate().find()报空指针异常
[color=darkred][/color] applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"> </property> <property name="url" value="jdbc:microsoft:sqlserver://localhost:1433;databasename=zf"> </property> <property name="username" value="sa"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.show_sql"> true </prop> </props> </property> <property name="mappingResources"> <list> <value>com/chen/model/TblFwlx.hbm.xml</value> <value>com/chen/model/TblFwxx.hbm.xml</value> <value>com/chen/model/TblJd.hbm.xml</value> <value>com/chen/model/TblQx.hbm.xml</value> <value>com/chen/model/TblUser.hbm.xml</value></list> </property></bean> <bean name="FwxxDao" class="com.cao.dao.FwxxDao"/> <bean name="LoginDao" class="com.cao.dao.LoginDao"/> </beans> applicationcontext-aop.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd" default-autowire="byName" default-lazy-init="true"> <!-- 以AspectJ方式 定义 AOP --> <aop:config proxy-target-class="true"> <aop:advisor pointcut="execution(* com.cao.dao.*Dao.*(..))" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" propagation="REQUIRED" read-only="true"/> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> </beans> FwxxAction代码: public class FwxxAction extends DispatchAction { private FwxxDao fwxxDao; public FwxxDao getFwxxDao() { return fwxxDao; } public void setFwxxDao(FwxxDao fwxxDao) { this.fwxxDao = fwxxDao; } @Override protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return doList(mapping, form, request, response); } public ActionForward doList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("in..........doList"); System.out.println("fwxxDao======="+fwxxDao); int index=1; int pageSize=5; try{ String str=request.getParameter("index"); index=Integer.parseInt(str); }catch(Exception e){ } List list=fwxxDao.getAll(); request.setAttribute("list", list); return mapping.findForward("fwxxList"); } } Dao代码: package com.cao.dao; import java.util.List; import com.cao.model.tblFwxx; public class FwxxDao extends BaseDao<tblFwxx> { public FwxxDao() { super.cls=tblFwxx.class; } public List getFwxx(){ return super.getAll(); } } BaseDao代码: public class BaseDao<T> extends HibernateDaoSupport { protected Class cls; public List<T> getAll(){ return getHibernateTemplate().findByExample(cls); } } struts-config.xml: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans > <form-bean name="fwxxForm" type="com.cao.struts.form.FwxxForm" /> </form-beans> <global-exceptions /> <global-forwards ></global-forwards> <action-mappings > <action attribute="fwxxForm" name="fwxxForm" parameter="method" path="/fwxx" scope="request" type="com.cao.struts.action.FwxxAction" > <forward name="fwxxList" path="/WEB-INF/jsp/FwxxList.jsp"></forward> </action> </action-mappings> <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/> <message-resources parameter="com.chen.struts.ApplicationResources" /> <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"/> </struts-config> action-servlet.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" default-autowire="byName"> <bean name="/fwxx" class="com.cao.struts.action.FwxxAction"/> </beans> web.xml代码: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext-*.xml</param-value> </context-param> <!-- 著名 Character Encoding filter --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <!--Hibernate Open Session in View Filter控制Session的连接--> <filter> <filter-name>hibernateFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <filter-mapping> <filter-name>hibernateFilter</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> 最后运行,getHibernateTemplate()为空,调用它的find方法抛空指针异常 用ApplicationContext con=new ClassPathXmlApplicationContext("applicationContext-*.xml"); con.getBean("FwxxDao"); 可以得到对象并可以调它的方法
深夜疑惑:SH整合时,getSession()正确,getHibernateTemplate()报错
[size=medium] 1、applicationContext-common.xml: [code="java"] <!-- sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="configLocation"> <value>classpath:hibernate.cfg.xml</value> </property> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <!-- 设置哪些类哪些方法使用上面的事务 --> <aop:config> <aop:pointcut expression="execution(* com.spring.manager.*.*(..))" id="allManagerMethod"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod"/> </aop:config> <!-- 设置事务传播特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="modify*" propagation="REQUIRED"/> <tx:method name="*" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> [/code] 2、applicationContext-bean.xml: [code="java"] <bean id="userManager" class="com.spring.manager.UserMangerImp"> <property name="sessionFactory" ref="sessionFactory"/> <property name="logManager" ref="logManager"/> </bean> <bean id="logManager" class="com.spring.manager.LogManagerImp"> <property name="sessionFactory" ref="sessionFactory"/> </bean> [/code] 3、测试代码: [code="java"] BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext-*.xml"); UserManager um = (UserManager)factory.getBean("userManager"); User u = new User(); u.setId(1); u.setName("张三"); um.addUser(u); [/code] [/size] 4、UserManagerImp.java: [code="java"] public String addUser(User user) { [color=red] //Session session = (Session) this.getHibernateTemplate(); Session session = (Session) this.getSession();[/color] session.save(user); Log log = new Log(); log.setDetail("增加一个用户"); log.setTime(new Date()); log.setType("查询"); logManager.addLog(log); return null; } [/code] 为什么使用getSession()正确执行,但是使用getHibernateTemplate()则报错,信息如下: [code="java"] [color=red]java.lang.ClassCastException: org.springframework.orm.hibernate3.HibernateTemplate cannot be cast to org.hibernate.Session[/color] at com.spring.manager.UserMangerImp.addUser(UserMangerImp.java:17) 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:307) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at $Proxy1.addUser(Unknown Source) at com.spring.test.UserMangerImpTest.testAddUser(UserMangerImpTest.java:29) 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 junit.framework.TestCase.runTest(TestCase.java:154) at junit.framework.TestCase.runBare(TestCase.java:127) at junit.framework.TestResult$1.protect(TestResult.java:106) at junit.framework.TestResult.runProtected(TestResult.java:124) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:118) at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) [/code]
HibernateDaoSupport使用疑惑?
``` public class AtableDaoImpl extends HibernateDaoSupport implements AtableDao{ @Override public void saveInfo(Atable a){ getHibernateTemplate().save(a); } } ``` Spring整合Hibernate 如果插入数据失败业务怎么处理异常呢?小白不懂求教
struts2与spring整合后测试时报空指针错误,急死了,跪求高手指点,非常感谢!
beans.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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <context:annotation-config /> <context:component-scan base-package="com.bjsxt" /> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:jdbc.properties</value> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp2.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>com.bjsxt.registration.model.User</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="userDao" class="com.bjsxt.registration.dao.impl.UserDaoImpl" scope="prototype"> </bean> <bean id="userManager" class="com.bjsxt.registration.service.impl.UserManagerImpl" scope="prototype"> <!-- 注入UserDao --> <property name="userDao" ref="userDao" /> </bean> <bean id="user" class="com.bjsxt.registration.action.UserAction" scope="prototype"> <!-- 注入Service --> <property name="userManager" ref="userManager" /> </bean> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <aop:config> <aop:pointcut id="bussinessService" expression="execution(public * com.bjsxt.registration.service.*.*(..))" /> <aop:advisor pointcut-ref="bussinessService" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="exists" read-only="true" /> <tx:method name="add*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> </beans> UserAction类中的代码如下: package com.bjsxt.registration.action; import com.bjsxt.registration.model.User; import com.bjsxt.registration.service.UserManager; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private String username; private String password; private String password2; private UserManager userManager; public UserManager getUserManager() { return userManager; } public void setUserManager(UserManager userManager) { this.userManager = userManager; } @Override public String execute() throws Exception { User u = new User(); u.setUsername(username); u.setPassword(password); if (userManager.exists(u)) { return "fail"; } userManager.add(u); return "success"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPassword2() { return password2; } public void setPassword2(String password2) { this.password2 = password2; } } UserDaoImpl类中的代码如下 package com.bjsxt.registration.dao.impl; import java.util.List; import org.springframework.orm.hibernate4.HibernateTemplate; import com.bjsxt.registration.dao.UserDao; import com.bjsxt.registration.model.User; public class UserDaoImpl implements UserDao { private HibernateTemplate hibernateTemplate; public void save(User u) { hibernateTemplate.save(u); } public boolean checkUserExistsWithName(String username) { List<User> users = (List<User>) hibernateTemplate.find("from User u where u.username = '" + username + "'"); if (users != null && users.size() > 0) { return true; } return false; } public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } } UserManagerImpl类中的代码如下 package com.bjsxt.registration.service.impl; import com.bjsxt.registration.dao.UserDao; import com.bjsxt.registration.model.User; import com.bjsxt.registration.service.UserManager; public class UserManagerImpl implements UserManager { private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } /* * (non-Javadoc) * * @see com.bjsxt.registration.service.impl.UserManager#exists(com.bjsxt. * registration.model.User) */ public boolean exists(User u) throws Exception { return userDao.checkUserExistsWithName(u.getUsername()); } /* * (non-Javadoc) * * @see com.bjsxt.registration.service.impl.UserManager#add(com.bjsxt. * registration.model.User) */ public void add(User u) throws Exception { userDao.save(u); } } 测试异常如下: ![图片说明](https://img-ask.csdn.net/upload/201608/20/1471674886_914285.jpg)
请教hibernate.connection.autocommit的问题
用Spring整合Hibernate。没有用事务,Spring配置如下: [code="java"]<beans> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/mydb"></property> <property name="username" value="root"></property> <property name="password" value="root"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> [color=red]<prop key="hibernate.connection.autocommit">false</prop>[/color] </props> </property> <property name="mappingResources"> <list> <value>vo/Student.hbm.xml</value> </list> </property> </bean> </beans>[/code] public class StudentDaoImpl extends HibernateDaoSupport implements StudentDao{ public void save(Student stu) { [color=red]this.getHibernateTemplate().save(stu); //问题:为什么上面设置autocommit为false,但这里还是会提交到数据库中[/color] } } [b]问题补充:[/b] 谢谢你的回复。 我用的是MySQL,但我发现即使加个声明式事务,调用getHibernateTemplate().save(stu)方法还是会插入到数据库中。以下是我的事务配置: <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref local="sessionFactory"/> </property> </bean> <bean id="studentDaoProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="transactionAttributes"> <props> <prop key="*">PROPAGATION_REQUIRED</prop> </props> </property> <property name="target"> <ref local="studentDao"/> </property> </bean> <bean id="studentDao" class="vo.StudentDaoImpl"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> 这是我的测试类: public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao studentDao = (StudentDao)context.getBean("studentDaoProxy"); //添加操作 Student student = new Student(); student.setName("测试"); studentDao.save(student); } }
spring 注解方面的疑惑
小弟最近刚刚接触ssh2整合 ,有2个问题没弄明白,希望各位高手 指教一下,小弟不胜感激 下面把我的代码先贴出来 [color=red]user.java[/color] public class User { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } [color=red]user.hbm.xml[/color] <?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="cn.com.jyp.model"> <class name="User" table="j_user"> <id name="id"> <generator class="native" /> </id> <property name="name" /> </class> </hibernate-mapping> [color=red]UserDao[/color] public interface UserDao { /** * 添加 */ public void save(User user); [color=red]UserDaoImpl[/color] @Repository("userDao") public class UserDaoImpl extends HibernateDaoSupport implements UserDao { @Resource(name = "hibernateTemplate") public void setHibernateTemplate1(HibernateTemplate hibernateTemplate) { super.setHibernateTemplate(hibernateTemplate); } /* * 添加 */ public void save(User user) { getHibernateTemplate().save(user); } [color=red]UserService[/color] public interface UserService { /** * 注册用户 */ public void save(User user); [color=red]UserServiceImpl[/color] @Service("userService") @Transactional public class UserServiceImpl implements UserService { @Resource private UserDao userDao; /* * 注册用户 */ public void save(User user) { if (user != null && user instanceof Object) userDao.save(user); } [color=red]struts.xml[/color] <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.objectFactory" value="spring" /> <package name="User" extends="struts-default"> <action name="userAdd" class="userAddAction"> <result name="success" >/success.jsp</result> <result name="input">/userAdd.jsp</result> </action> </package> </struts> [color=red]applicationContext.xml[/color] <?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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- spring自动扫描和管理bean --> <context:component-scan base-package="cn.com.jyp"/> <!-- 配置数据源 --> <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/ssh2" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- 配置SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="mappingResources"> <list> <value>cn/com/jyp/model/User.hbm.xml</value> </list> </property> </bean> <!-- 配置hibernateTemplate --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置spring提供的事务管理器 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 采用@Transactional注解方式使用事务 --> <tx:annotation-driven transaction-manager="txManager"/> </beans> 我的疑问是,第一个:在使用Spring提供的注解方式@Resource 注入依赖对象,标注在属性上,是不是可以不用提供这个属性的setter方法,如果可以不提供的话,为什么UserDaoImpl 里 这么写 @Resource private HibernateTemplate hibernateTemplate; 确出错,这个注解的实现原理是不是根据相应的属性自动提供其setter方法为其注入的啊 ? 第二个:关于事务的注解是按照上面的代码这么标在service上吧? 第三个:就是请各位帮我看看我的代码不足之处 谢谢了!
mysql 和proxool 数据库连接池的问题(连接定时递增)
我在Struts2.0 + Spring2.0 + hibernate3.2的应用中采用了proxool 数据库连接池。 proxool.xml的配置如下: <?xml version="1.0" encoding="utf-8"?> <something-else-entirely> <proxool> <alias>test</alias> <driver-url>jdbc:mysql://127.0.0.1:3306/testdb?useUnicode=true&amp;characterEncoding=utf-8</driver-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <driver-properties> <property name="user" value="root"/> <property name="password" value="root"/> </driver-properties> <house-keeping-test-sql>select CURRENT_DATE</house-keeping-test-sql> <house-keeping-sleep-time>90000</house-keeping-sleep-time> <prototype-count>5</prototype-count> <maximum-connection-count>100</maximum-connection-count> <minimum-connection-count>10</minimum-connection-count> </proxool> </something-else-entirely> 在applicationContext.xml中 <!-- Hibernate-Spring配置 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="mappingResources"> <list> <value>com/test/User.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.connection.autocommit">true</prop> <prop key="hibernate.connection.release_mode">after_statement</prop> <prop key="hibernate.bytecode.use_reflection_optimizer">true</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> <prop key="hibernate.connection.provider_class">org.hibernate.connection.ProxoolConnectionProvider</prop> <prop key="hibernate.proxool.xml">proxool.xml</prop> <prop key="hibernate.proxool.pool_alias">test</prop> </props> </property> </bean> MySqL 的 my.ini 配置参数 max_connections=500 interactive_timeout=10000000 wait_timeout=10000000 proxool 的 maximum-connection-lifetime(连接最大生命时间)默认4小时,发现每隔4个小时,通过show status命令查看MySQl 的Connections 增加10个,很快就会到达max_connections的最大限制,虽然可以把max_connections设置为16000,但是这只是延长出问题的时间而已。请各位遇到这样情况的朋友指导如何解决? MySQL 版本5.0和4.1都试过,proxool 版本为 proxool-0.9.0RC3。 [b]问题补充:[/b] 蔡华江:谢谢指点。我在数据库的查询、更新等方面都是通过hibernate来完成的,如查询用户 public User findUserByUsername(String username) { String queryStr=PropertyOwner.getKeyValue("getuserwithname"); Session session = this.getSession(); Query query=getQuery(queryStr,session); query.setString("username", username); if(query.list().size()>0) { User tmp=(User)query.list().get(0); this.closeSession(session); return tmp; } else { this.closeSession(session); return null; } } 在程序的最后都有this.closeSession(session);这样的语句,难道数据连接没有关闭? [b]问题补充:[/b] 现在我怀疑是 this.closeSession(session); 没有关闭连接。因为Session session = this.getSession(); 利用getSession强制获得了Hibernate的 Session,这个Session可能是当前事务中之前使用过的,或者可能是一个新的,并不在当前事务中,Spring只对当前事务中的Session 进行关闭。参考“spring整合hibernate关于session的管理”(http://solodu.iteye.com/blog/454469),我修改Session session = super.getSession(true);运行10分钟后还是递增连接。说明还有其他的数据库连接没有释放。查看Proxool的监控界面可以看到连接情况0 (active), 10 (available), 100 (max)。 我怀疑一个定时保存的地方有问题 try { otherDAO.updataOrSave(tmpp); } catch (Exception e) { } ......>跟踪 public void updataOrSave(T domainObject) throws Exception { saveOrUpdate((Object)domainObject); } ......>继续跟踪 protected void saveOrUpdate(final Object obj)throws Exception { run ( new TransactionRunnable () { public Object run (Session s) { saveOrUpdate(obj, s); return null; } }); } ......>继续跟踪 protected void saveOrUpdate(Object obj, Session s) { s.saveOrUpdate(obj); } 请问上述代码有问题吗? [b]问题补充:[/b] 现在我把定时保存部分关闭了,照样有此问题。 [b]问题补充:[/b] 经过多次试验,增加连接的地方是类似这样的hibernate的操作 public History queryHistory(String queryStr,String entity,Date time) { Session session = this.getHibernateTemplate().getSessionFactory().openSession();//该句照样增加连接数 //getSession();//该句照样增加连接数 Query query=super.getQuery(queryStr,session); int size=query.list().size(); if(size>0) { History temp=(History)query.list().get(0); session.close(); return temp; } else { session.close(); return null; } } [b]问题补充:[/b] 现在问题是Proxool连接池里的连接ID老是递增(通过Proxool监控界面看),连接数是没有超过最大连接。请问各位好手如何解决啊? [b]问题补充:[/b] 这个问题竟然是我的理解错了。 MySQL的SHOW STATUS提供服务器的状态信息: Connections 试图连接MySQL服务器的次数,是不断增加,不是真正的目前连接数(与MySqL 的 my.ini 配置参数 max_connections无关,好多人都理解错误)。 真正有用的是下述几个 Threads_created 表示创建过的线程数,该值太大,就要增加my.cnf中thread_cache_size的值 Threads_connected 当前打开的连接的数量。 Threads_running 不在睡眠的线程数量。 Aborted_clients 由于客户没有正确关闭连接已经死掉,已经放弃的连接数量。 Aborted_connects 尝试已经失败的MySQL服务器的连接的次数。 感谢蔡华江的指导。
ssh的spring 无法注入怎么回事
<strong>UserInfoDAOImpl.java</strong> <br /><pre name="code" class="java">@Service public class UserInfoDAOImpl extends HibernateDaoSupport implements UserInfoDAO { public boolean login(Userinfo userinfo) { boolean isExist = false; Userinfo temp = (Userinfo)this.getHibernateTemplate().find("from Userinfo u where u.username=?", userinfo.getUsername()).get(0); try { if(userinfo.getPassword().equals(temp.getPassword())) isExist = true; } catch(Exception e) { e.printStackTrace(); } System.out.println("id:" + temp.getId()); System.out.println("username:" + temp.getUsername()); System.out.println("password:" + temp.getPassword()); System.out.println("isExist:" + isExist); return isExist; } }</pre> <br /><strong>LoginAction.java</strong> <br /><pre name="code" class="java">@Component @Results(value={ @Result(name="success", location="/login_success.jsp"), @Result(name="fail", location="/Login.jsp") }) public class LoginAction extends ActionSupport { private Userinfo userinfo; @Autowired private UserInfoDAO userInfoDAOImpl; public Userinfo getUserinfo() { return userinfo; } public void setUserinfo(Userinfo userinfo) { this.userinfo = userinfo; } public UserInfoDAO getUserInfoDAOImpl() { return userInfoDAOImpl; } public void setUserInfoDAOImpl(UserInfoDAO userInfoDAOImpl) { System.out.println("注入"); this.userInfoDAOImpl = userInfoDAOImpl; } @Action("login") public String login() { System.out.println("id:" + userinfo.getId()); System.out.println("username:" + userinfo.getUsername()); System.out.println("password:" + userinfo.getPassword()); if(userInfoDAOImpl == null) System.out.println("error"); if(userinfo == null) return "fail"; else return (userInfoDAOImpl.login(userinfo))?"success":"fail"; } }</pre> <br /><strong>applicationContext.xml</strong> <br /><pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" 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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-lazy-init="true"&gt; &lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /&gt; &lt;property name="ignoreResourceNotFound" value="true" /&gt; &lt;property name="locations"&gt; &lt;list&gt; &lt;value&gt;classpath:application.properties&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;context:component-scan base-package="org.sales.dao.Impl" /&gt; &lt;!-- 数据源配置,使用应用内的DBCP数据库连接池 --&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;!-- Connection Info --&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;property name="namingStrategy"&gt; &lt;bean class="org.hibernate.cfg.ImprovedNamingStrategy" /&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;${hibernate.dialect}&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;${hibernate.show_sql}&lt;/prop&gt; &lt;prop key="hibernate.format_sql"&gt;${hibernate.format_sql}&lt;/prop&gt; &lt;prop key="hibernate.cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/prop&gt; &lt;!-- &lt;prop key="hibernate.cache.provider_configuration_file_resource_path"&gt;${hibernate.ehcache_config_file}&lt;/prop&gt;--&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="packagesToScan" value="org.sales.entity" /&gt; &lt;property name="annotatedClasses"&gt; &lt;list&gt; &lt;value&gt;org.sales.entity.Iteminfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Cardinfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Positioninfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Sellinfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Userinfo&lt;/value&gt; &lt;value&gt;org.sales.entity.Voteinfo&lt;/value&gt;&lt;/list&gt; &lt;/property&gt;&lt;/bean&gt; &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" &gt; &lt;property name="sessionFactory" ref="sessionFactory"/&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;bean id="CardinfoDAO" class="org.sales.entity.CardinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="IteminfoDAO" class="org.sales.entity.IteminfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="PositioninfoDAO" class="org.sales.entity.PositioninfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="SellinfoDAO" class="org.sales.entity.SellinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="UserinfoDAO" class="org.sales.entity.UserinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="VoteinfoDAO" class="org.sales.entity.VoteinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <br /><strong>web.xml</strong> <br /><pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;classpath*:applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;filter&gt; &lt;filter-name&gt;OpenSessionInViewFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.orm.hibernate3.support.OpenSessionInViewFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;singleSession&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;filter&gt; &lt;filter-name&gt;struts2Filter&lt;/filter-name&gt; &lt;filter-class&gt;org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;struts2Filter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;OpenSessionInViewFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt; </pre> <br /> <br />结果在LoginAction.java里面输出: <br />id:null <br />username:username <br />password:USERNAME <br />error <br />说明: error是当被注入的属性为空的时候输出. <br /> 求解~ <br /> <br /><strong>异常(网页上的):</strong> <br />HTTP Status 500 - <br /> <br />type Exception report <br /> <br />message <br /> <br />description The server encountered an internal error () that prevented it from fulfilling this request. <br /> <br />exception <br /> <br />java.lang.NullPointerException <br /> org.sales.actions.LoginAction.login(LoginAction.java:53) <br /> sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) <br /> sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) <br /> sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) <br /> java.lang.reflect.Method.invoke(Method.java:597) <br /> com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) <br /> com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) <br /> com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243)<br/><strong>问题补充</strong><br/><div class="quote_title">xixix2004 写道</div><div class="quote_div">有异常吗。<br /> <br />敢不敢把异常发出来看一下。</div><br />发了<br/><strong>问题补充</strong><br/><div class="quote_title">xixix2004 写道</div><div class="quote_div">好吧,应该不需要异常,请把ACTION里定义的DAO的变量名,变得和xml里定义的BEAN ID属性一致。</div><br />xml里面没有对应的bean,因为使用注释<br/><strong>问题补充</strong><br/><div class="quote_title">yyf365 写道</div><div class="quote_div">可能和楼主的应用写法不太相同,请问你其他的service是否能注入成功呢?,不过是否能试试在applicationContext配置文件中的声明方式换一种呢?<br /><br />如:<br />&lt;bean id="UserInfoDAO"<br /> class="UserInfoDAOImp"&gt;<br /> &lt;/bean&gt;<br />这种形式注入,实例化由spring托管,而在action中只对UserInfoDAO的service进行注入呢<br /><br />而如果出了该service无法注入外,其他其余的service都能正常注入使用,那就另想办法了</div><br /> 可是这种方法有点麻烦,我想实现注释注入,xml文件里面有个扫描的:<br /> &lt;context:component-scan base-package="org.sales.dao.Impl" /&gt;&nbsp; <br/><strong>问题补充</strong><br/>已经试过在 <strong>applicationContext.xml</strong> 文件里面添加<br /><pre name="code" class="xml">&lt;bean id="userInfoDAOImpl" class="org.sales.dao.Impl.UserInfoDAOImpl"&gt; &lt;/bean&gt; &lt;bean id="loginAction" class="org.sales.actions.LoginAction"&gt; &lt;property name="userInfoDAOImpl"&gt; &lt;ref bean="userInfoDAOImpl" /&gt; &lt;/property&gt; &lt;/bean&gt;</pre><br /><br />异常信息一样.<br/><strong>问题补充</strong><br/><div class="quote_title">xixix2004 写道</div><div class="quote_div"><div class="quote_title">bbinglongg 写道</div><div class="quote_div"><div class="quote_title">xixix2004 写道</div><div class="quote_div">好吧,应该不需要异常,请把ACTION里定义的DAO的变量名,变得和xml里定义的BEAN ID属性一致。</div><br />xml里面没有对应的bean,因为使用注释</div><br /><br /><br />你完全没看懂我在说什么。<br /><br /><pre name="code" class="java">private UserInfoDAO userinfoDAO; </pre><br /><pre name="code" class="java"> &lt;bean id="userinfoDAO" class="org.sales.entity.UserinfoDAO"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory" /&gt; &lt;/property&gt; &lt;/bean&gt; </pre><br /><br /><br /><br /></div><br />在它上面有一句:<br /><pre name="code" class="java">@Autowired</pre><br />是自动注入的意思<br/><strong>问题补充</strong><br/><div class="quote_title">xixix2004 写道</div><div class="quote_div">&lt;ref bean="UserInfoDAO" /&gt;这里的REF的BEAN, 写你之前定义的BEAN的ID。你可明白?</div><br />明白<br/><strong>问题补充</strong><br/><div class="quote_title">dwbin 写道</div><div class="quote_div">loginAction没有进行spring托管。<br />这个类spring不会自己进行注入的。你的ssh整合有问题</div><br /><br />那我应该怎么修改呢?<br/><strong>问题补充</strong><br/><div class="quote_title">dwbin 写道</div><div class="quote_div">loginAction没有进行spring托管。<br />这个类spring不会自己进行注入的。你的ssh整合有问题</div><br />在 <pre name="code" class="java">@Autowired</pre> 这个标签里面已经是注入了
SSH整合问题 NullPointerException
SSH整合的一个小例子,struts2+Spring2+Hibernate3 代码如下: Person.java [code="java"] package com.eva.po; /** * Person entity. * * @author eva */ import java.io.Serializable; public class Person implements Serializable{ private int id; private String name; private int age; private String sex; private String address; /** defult constructor */ public Person() { } /** minimal constructor */ public Person(String name) { this.name = name; } /** full constructor */ public Person(String name,int age,String sex,String address) { this.name = name; this.age = age; this.sex = sex; this.address = address; } //setter and getter } [/code] PersonDAO.java [code="java"] package com.eva.dao; import java.util.List; import com.eva.po.Person; public interface PersonDAO { public void saveOrUpdate(Person person); public void update(Person person); public void delete(Person person); public Person get(String id); public List<Person> findAll(); } [/code] PersonHibernateDAO.java [code="java"] package com.eva.dao.hibernate; import java.util.List; import com.eva.dao.PersonDAO; import com.eva.po.Person; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class PersonHibernateDAO extends HibernateDaoSupport implements PersonDAO { public void delete(Person person) { this.getHibernateTemplate().delete(person); } public List<Person> findAll() { List<Person> persons = this.getHibernateTemplate().find("from Person"); return persons; } public Person get(String id) { Person person = (Person)this.getHibernateTemplate().get(Person.class, id); return person; } public void saveOrUpdate(Person person) { this.getHibernateTemplate().saveOrUpdate(person); } public void update(Person person) { this.getHibernateTemplate().saveOrUpdate(person); } } [/code] PersonService.java [code="java"] package com.eva.service; import java.util.List; import com.eva.dao.hibernate.PersonHibernateDAO; import com.eva.po.Person; public class PersonService { private PersonHibernateDAO personHibernateDAO; public void setPersonHibernateDAO(PersonHibernateDAO personHibernateDAO) { this.personHibernateDAO = personHibernateDAO; System.out.println("personHibernateDAO is null ? --- " + personHibernateDAO == null); } public PersonHibernateDAO getPersonHibernateDAO() { return personHibernateDAO; } public void saveOrUpdate(Person person) { personHibernateDAO.saveOrUpdate(person); } public void update(Person person) { personHibernateDAO.update(person); } public void delete(Person person) { personHibernateDAO.delete(person); } public List<Person> findAll() { return personHibernateDAO.findAll(); } public Person get(String id) { return personHibernateDAO.get(id); } } [/code] LoginAction.java [code="java"] package com.eva.action; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import com.eva.po.Person; import com.eva.service.PersonService; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private PersonService personService; private Person person; private String id; private List<Person> persons; public LoginAction() { } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getId() { return id; } public void setId(String id) { this.id = id; } public PersonService getPersonService() { return personService; } public void setPersonService(PersonService personService) { this.personService = personService; } public List<Person> getPersons() { return persons; } public void setPersons(List<Person> persons) { this.persons = persons; } public String execute() throws Exception { if (person != null & !person.equals("")) { personService.saveOrUpdate(person); } persons = personService.findAll(); setPersons(persons); System.out.println(persons.size()); return SUCCESS; } public String list() throws Exception { persons = personService.findAll(); setPersons(persons); return SUCCESS; } public String save() throws Exception {; personService.saveOrUpdate(person); return SUCCESS; } public String update() throws Exception { person = personService.get(id); personService.update(person); return SUCCESS; } public String getValue() throws Exception { return SUCCESS; } public String delete() throws Exception{ person = personService.get(id); personService.delete(person); return SUCCESS; } } [/code] applicationContext.xml [code="java"] <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> <!-- dataSource配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value> </property> <property name="url"> <value> jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=ssh </value> </property> <property name="username"> <value>sa</value> </property> <property name="password"> <value>sa</value> </property> </bean> <!-- 配置session工厂 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource"/> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> </props> </property> <property name="mappingResources"> <list> <value>com/eva/po/Person.hbm.xml</value></list> </property> </bean> <!-- 具体的数据库访问类 --> <bean id="dao" class="com.eva.dao.hibernate.PersonHibernateDAO"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <!-- 配置具体的业务逻辑类 --> <bean id="personService" class="com.eva.service.PersonService"> <property name="personHibernateDAO"> <ref bean="dao"/> </property> </bean> <!-- 配置action --> <bean id="loginAction" class="com.eva.action.LoginAction"> <property name="personService"> <ref bean="personService"/> </property> </bean> </beans> [/code] struts.xml [code="java"] <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 一定要加,对象工厂是spring --> <constant name="struts.objectFactory" value="spring" /> <!-- 开启开发模式 --> <constant name="struts.devMode" value="true" /> <package name="login" extends="struts-default"> <!-- 保存 --> <action name="Login" method="save" class="com.eva.action.LoginAction"> <result>success.jsp</result> <!-- <result name="error">error.jsp</result> --> </action> <!-- 显示出所有列表 --> <action name="list" method="list" class="com.eva.action.LoginAction"> <result>success.jsp</result> </action> <!-- 删除 --> <action name="delete" method="delete" class="com.eva.action.LoginAction"> <result>success.jsp</result> </action> <!-- 更新 --> <action name="update" method="update" class="com.eva.action.LoginAction"> <result>index.jsp</result> </action> </package> </struts> [/code] Person.hbm.xml [code="java"] <?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"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="org.s2s2h3.po.Person" table="person_" catalog="ssh2"> <id name="id" type="java.lang.String"> <column name="id" length="10" /> <generator class="assigned" /> </id> <property name="name" type="java.lang.String"> <column name="name" length="30" not-null="true" /> </property> <property name="age" type="java.lang.String"> <column name="age" length="10" /> </property> <property name="sex" type="java.lang.String"> <column name="sex" length="10" /> </property> <property name="address" type="java.lang.String"> <column name="address" length="50" /> </property> </class> </hibernate-mapping> [/code] web.xml [code="java"] <?xml version="1.0" encoding="UTF-8"?> <web-app id="person" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>person</display-name> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> <init-param> <param-name>classes</param-name> <param-value>java.lang.Object</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext*.xml</param-value> </context-param> <!-- 添加监听器 --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> [/code] index.jsp [code="java"] <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <s:if test="null == person"> Add Person </s:if> <s:else> Update Person </s:else> <s:form action="Login" method="post"> <table> <caption> 客户管理 </caption> <tr> <td> <s:textfield name="person.id" label="ID" /> </td> </tr> <tr> <td> <s:textfield name="person.name" label="NAME" /> </td> </tr> <tr> <td> <s:textfield name="person.age" label="AGE" /> </td> </tr> <tr> <td> <s:textfield name="person.sex" label="SEX" /> </td> </tr> <tr> <td> <s:textfield name="person.address" label="ADDRESS" /> </td> </tr> <tr> <td colspan="2"> <s:submit value="submit" /> <s:reset value="reset" /> </td> </tr> </table> </s:form> </body> </html> [/code] 添加数据之后点提交,会抛空指针错误,原因是LoginAction.java中的personService为空。。。 困惑,希望路过的各位兄弟帮忙看看。。谢过先~~
SSH整合异常
<p>最近在项目中出现了一些奇怪问题,还是说说我的目的吧,我想要在数据库中随机抽取一定数量且符合要求的记录,第一种实现,dao的一个方法为:</p> <p><span style="white-space: pre;"> </span><span style="white-space: pre;">public List&lt;Calking&gt; find3type(String str2) {</span></p> <pre name="code" class="java"> // TODO Auto-generated method stub List&lt;Calking&gt; list = new ArrayList&lt;Calking&gt;();//用来存放最终的结果集 List&lt;Calking&gt; list1 = null;//用来存储中间查到的所有符合条件的结果 List&lt;Integer&gt; list2;//用来存放生成的随机数数组 Query q=this.getHibernateTemplate().getSessionFactory().openSession().createQuery("from Calking as ca where ca.degree=?"); q.setString(0, str2); list1=q.list(); int n=list1.size();//用来得到符合条件的结果的个数 Suiji s5=(Suiji) new Suiji5(); list2=s5.take(n); Iterator&lt;Integer&gt; iterator=list2.iterator(); while(iterator.hasNext()){ int j=(Integer)iterator.next(); Calking cal=(Calking)list1.get(j-1); list.add(cal); } return list; }</pre> <p> <span style="white-space: pre;"> </span>这样我在service里调用dao,在action中就可以得到值了,这种实现已经ok了,可是这样对于系统的消耗太大,用数组存取对象,然后再用数组去过滤对象。第二种实现方式如下,不再是使用数组存取所有对象来选取,而是用数组</p> <p>存取所有符合条件的对象的id,然后按照id来加载对象。</p> <p><span style="white-space: pre;"> </span><span style="white-space: pre;">List&lt;Calking&gt; list = new ArrayList&lt;Calking&gt;();//用来存放加载的对象</span></p> <pre name="code" class="java"> List&lt;Integer&gt; list1 = new ArrayList&lt;Integer&gt;();//用来存放最终用来加载对象而生成的id List&lt;Integer&gt; list2;//用来存放生成的随机数 List&lt;Integer&gt; list3;//用来存放查出来的所有id //Query q1=this.getHibernateTemplate().find("select ca.id from Calking as ca where ca.degree="+str); //q1.setString(0, ); //list3=q1.list(); list3=this.getHibernateTemplate().find("select ca.id from Calking as ca where ca.degree=?",str); System.out.println(list3);//1 int n=list3.size(); Suiji sx=new Suiji10(); list2=sx.take(n); Iterator iterator1=list2.iterator(); while(iterator1.hasNext()){ int j=(Integer)iterator1.next(); int k=list3.get(j-1); list1.add(k); } System.out.println(list1);//2 //Iterator iterator2=list1.iterator(); /* while(iterator2.hasNext()){ int z=(Integer)iterator2.next(); System.out.print(z+" ");//3 Calking cal=(Calking) this.getHibernateTemplate().getSessionFactory().openSession().get(Calking.class, z);//按照随机数作为id来加载对象 //Calking cal=(Calking) this.getHibernateTemplate().getSessionFactory().openSession().get(Calking.class, z); list.add(cal); }*/ for(int a=0;a&lt;list1.size();a++){ int b=list1.get(a); System.out.print(b); Calking cal=(Calking) this.getHibernateTemplate().load(Calking.class, b);//按照随机数作为id来加载对象 System.out.println(cal); list.add(cal); } System.out.println(list.size());//此处没有打印出对象,估计是没有加载上,问题为加载的对象为7个,打印得到的随机数为8个 return list; }</pre> <p> <span style="white-space: pre;"> </span>现在问题是上面写的那样,而且现在有一个异常:</p> <p><span style="white-space: pre;"> </span><span style="white-space: pre;">org.hibernate.LazyInitializationException: could not initialize proxy - no Session</span></p> <pre name="code" class="java"> org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:57) org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:111) org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150) com.zq.model.Calking$$EnhancerByCGLIB$$6a3f08af.toString(&lt;generated&gt;)</pre> <p>问题解决中,也期待看到的高人们指点指点。谢谢。</p> <p> </p><br /><strong>问题补充:</strong><br />问题已解决,主要还是配置问题,一楼的方案之前我也用过,配上去就错,不过现在改变了一些配置还是解决了,用的是OpenSessionInViewFilter,这样可以保证session链接不会被用完,而且这个配置好像得配到struts2的filter之前 <br />&lt;filter&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;filter-name&gt;OpenSessionInViewFilter&lt;/filter-name&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;filter-class&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; org.springframework.orm.hibernate3.support.OpenSessionInViewFilter <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/filter-class&gt; <br />&nbsp;&nbsp;&nbsp; &lt;/filter&gt; <br />&nbsp;&nbsp;&nbsp; &lt;filter-mapping&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;filter-name&gt;OpenSessionInViewFilter&lt;/filter-name&gt; <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; <br />&nbsp;&nbsp;&nbsp; &lt;/filter-mapping&gt;&nbsp; <br /> &lt;filter&gt;,现在ok了,谢谢关注
SSH整合问题 定义两个action后无法实现注入
我用SSH做了个java web项目,hibernate我是用注解的方式,spring我用xml来配置,首先我定义了一个user Model,以及它对应的userDao,userDaoImpl,userService,userServiceImpl,发现可以正确运行,然后我定义了和user完全一样的people Model,代码如下 people: @Entity public class people { private int id; private String username; private String password; 省略set get方法 } peopleDaoImple: public class peopleImpl implements peopleDao { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public boolean save(people u) { hibernateTemplate.save(u); return true; } } peopleImpl: public class peopleImpl implements peopleService { private peopleDao peopledao; public peopleDao getPeopledao() { return peopledao; } public void setPeopledao(peopleDao peopledao) { this.peopledao = peopledao; } public boolean save(people u) { peopledao.save(u); return true; } } 对应的applicationContext的配置如下: <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" > <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.SQLServerDialect </prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <property name="annotatedClasses"> <list> <value>com.model.User</value> <value>com.model.people</value> </list> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" <property name="sessionFactory" ref="sessionFactory"></property> </bean> peopleDaoImpl的配置如下: <bean id="peopledao" class="com.Dao.Impl.peopleImpl" > <property name="hibernateTemplate" ref="hibernateTemplate"></property> </bean> peopleImpl配置如下: <bean id="peopleService" class="com.ServiceDao.Impl.peopleImpl" > <property name="peopledao" ref="peopledao"></property> </bean> 我觉得奇怪的是 我单单配置一个user时程序没问题,而多加了一个people以后则没办法用spring来为people注入,运行时tomcat服务器没有问题,但浏览器上出现错误500 然后报 java.lang.NullPointerException com.ServiceDao.Impl.peopleImpl.save(peopleImpl.java:21) com.Actions.peopleAction.Register(peopleAction.java:44) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) java.lang.reflect.Method.invoke(Method.java:597) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:163) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:249) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:148) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:128) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.ProfilingActivationInterceptor.intercept(ProfilingActivationInterceptor.java:104) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:148) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:128) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)
S2SH整合时报错多谢各位
<p>hibernate配置文件</p> <pre name="code" class="xml">&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"&gt; &lt;!-- Generated by MyEclipse Hibernate Tools. --&gt; &lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name="dialect"&gt; org.hibernate.dialect.MySQLDialect &lt;/property&gt; &lt;property name="connection.url"&gt; jdbc:mysql://localhost:3306/mydb &lt;/property&gt; &lt;property name="connection.username"&gt;root&lt;/property&gt; &lt;property name="connection.password"&gt;a&lt;/property&gt; &lt;property name="connection.driver_class"&gt; com.mysql.jdbc.Driver &lt;/property&gt; &lt;property name="myeclipse.connection.profile"&gt;mysql&lt;/property&gt; &lt;property name="hbm2ddl.auto"&gt;update&lt;/property&gt; &lt;mapping resource="com/james/domain/User.hbm.xml" /&gt; &lt;/session-factory&gt; &lt;/hibernate-configuration&gt;</pre> <p> </p> <p>spring配置文件</p> <p> </p> <p> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"&gt; &lt;context:annotation-config/&gt; &lt;context:component-scan base-package="com.james"/&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;property name="configLocation" value="classpath:hibernate.cfg.xml"&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"&gt; &lt;property name="sessionFactory" ref="hibernateTemplate"/&gt; &lt;/bean&gt; &lt;tx:annotation-driven transaction-manager="txManager"/&gt; &lt;/beans&gt;</pre> <p> userdaoImpl内容为</p> <p> </p> <p> </p> <p> </p> <pre name="code" class="java">package com.james.dao.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Component; import com.james.dao.UserDao; import com.james.domain.User; @Component public class UserDaoImpl implements UserDao { HibernateTemplate hibernateTemplate; public boolean del(int id) { // TODO Auto-generated method stub return false; } public List&lt;User&gt; findAll() { // TODO Auto-generated method stub return null; } public User findById(int id) { // TODO Auto-generated method stub return null; } public List&lt;User&gt; findByName(String userName) { // TODO Auto-generated method stub return null; } public boolean save(User user) { System.out.println("running here userdao save"); hibernateTemplate.save(user); // TODO Auto-generated method stub return false; } public boolean update(User user) { // TODO Auto-generated method stub return false; } public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } } </pre> <p> </p> <p>报错内容为</p> <p> </p> <pre name="code" class="java">Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateTemplate' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [org.springframework.orm.hibernate3.HibernateTemplate] to required type [org.hibernate.SessionFactory] for property 'sessionFactory'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.orm.hibernate3.HibernateTemplate] to required type [org.hibernate.SessionFactory] for property 'sessionFactory': no matching editors or conversion strategy found at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:168) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:435) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:409) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:537) at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:192) at org.springframework.beans.factory.annotation.InjectionMetadata.injectMethods(InjectionMetadata.java:117) at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:302) ... 40 more Caused by: org.springframework.beans.TypeMismatchException: Failed to convert property value of type [org.springframework.orm.hibernate3.HibernateTemplate] to required type [org.hibernate.SessionFactory] for property 'sessionFactory'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.orm.hibernate3.HibernateTemplate] to required type [org.hibernate.SessionFactory] for property 'sessionFactory': no matching editors or conversion strategy found at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:391) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1289) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1250) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1010) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:472) ... 54 more Caused by: java.lang.IllegalArgumentException: Cannot convert value of type [org.springframework.orm.hibernate3.HibernateTemplate] to required type [org.hibernate.SessionFactory] for property 'sessionFactory': no matching editors or conversion strategy found at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:231) at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:138) at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:386) ... 58 more</pre> <p> </p> <p>请问一下这是什么原因,我看网络上好多人都是利用myeclipse自动生成的配置文件搞的,我这个为什么就不行呢?</p> <p>多谢各位大侠</p>
终于明白阿里百度这样的大公司,为什么面试经常拿ThreadLocal考验求职者了
点击上面↑「爱开发」关注我们每晚10点,捕获技术思考和创业资源洞察什么是ThreadLocalThreadLocal是一个本地线程副本变量工具类,各个线程都拥有一份线程私...
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小人工智障。 思路可以运用在不同地方,主要介绍的是思路。
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
阿里面试官问我:如何设计秒杀系统?我的回答让他比起大拇指
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图和个人联系方式,欢迎Star和指教 前言 Redis在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在Redis的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸,打败了...
C语言魔塔游戏
很早就很想写这个,今天终于写完了。 游戏截图: 编译环境: VS2017 游戏需要一些图片,如果有想要的或者对游戏有什么看法的可以加我的QQ 2985486630 讨论,如果暂时没有回应,可以在博客下方留言,到时候我会看到。 下面我来介绍一下游戏的主要功能和实现方式 首先是玩家的定义,使用结构体,这个名字是可以自己改变的 struct gamerole { char n...
面试官问我:什么是消息队列?什么场景需要他?用了会出现什么问题?
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
Android性能优化(4):UI渲染机制以及优化
文章目录1. 渲染机制分析1.1 渲染机制1.2 卡顿现象1.3 内存抖动2. 渲染优化方式2.1 过度绘制优化2.1.1 Show GPU overdraw2.1.2 Profile GPU Rendering2.2 卡顿优化2.2.1 SysTrace2.2.2 TraceView 在从Android 6.0源码的角度剖析View的绘制原理一文中,我们了解到View的绘制流程有三个步骤,即m...
微服务中的Kafka与Micronaut
今天,我们将通过Apache Kafka主题构建一些彼此异步通信的微服务。我们使用Micronaut框架,它为与Kafka集成提供专门的库。让我们简要介绍一下示例系统的体系结构。我们有四个微型服务:订单服务,行程服务,司机服务和乘客服务。这些应用程序的实现非常简单。它们都有内存存储,并连接到同一个Kafka实例。 我们系统的主要目标是为客户安排行程。订单服务应用程序还充当网关。它接收来自客户的请求...
致 Python 初学者们!
作者| 许向武 责编 | 屠敏 出品 | CSDN 博客 前言 在 Python 进阶的过程中,相信很多同学应该大致上学习了很多 Python 的基础知识,也正在努力成长。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 Python 这门编程语言,从2009年开始单一使用 Python 应对所有的开发工作,直至今...
究竟你适不适合买Mac?
我清晰的记得,刚买的macbook pro回到家,开机后第一件事情,就是上了淘宝网,花了500元钱,找了一个上门维修电脑的师傅,上门给我装了一个windows系统。。。。。。 表砍我。。。 当时买mac的初衷,只是想要个固态硬盘的笔记本,用来运行一些复杂的扑克软件。而看了当时所有的SSD笔记本后,最终决定,还是买个好(xiong)看(da)的。 已经有好几个朋友问我mba怎么样了,所以今天尽量客观...
程序员一般通过什么途径接私活?
二哥,你好,我想知道一般程序猿都如何接私活,我也想接,能告诉我一些方法吗? 上面是一个读者“烦不烦”问我的一个问题。其实不止是“烦不烦”,还有很多读者问过我类似这样的问题。 我接的私活不算多,挣到的钱也没有多少,加起来不到 20W。说实话,这个数目说出来我是有点心虚的,毕竟太少了,大家轻喷。但我想,恰好配得上“一般程序员”这个称号啊。毕竟苍蝇再小也是肉,我也算是有经验的人了。 唾弃接私活、做外...
字节跳动面试官这样问消息队列:分布式事务、重复消费、顺序消费,我整理了一下
你知道的越多,你不知道的越多 点赞再看,养成习惯 GitHub上已经开源 https://github.com/JavaFamily 有一线大厂面试点脑图、个人联系方式和人才交流群,欢迎Star和完善 前言 消息队列在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在消息队列的使用和原理方面对小伙伴们进行360°的刁难。 作为一个在互联网公司面一次拿一次Offer的面霸...
Python爬虫爬取淘宝,京东商品信息
小编是一个理科生,不善长说一些废话。简单介绍下原理然后直接上代码。 使用的工具(Python+pycharm2019.3+selenium+xpath+chromedriver)其中要使用pycharm也可以私聊我selenium是一个框架可以通过pip下载 pip installselenium -ihttps://pypi.tuna.tsinghua.edu.cn/simple/ ...
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
Java工作4年来应聘要16K最后没要,细节如下。。。
前奏: 今天2B哥和大家分享一位前几天面试的一位应聘者,工作4年26岁,统招本科。 以下就是他的简历和面试情况。 基本情况: 专业技能: 1、&nbsp;熟悉Sping了解SpringMVC、SpringBoot、Mybatis等框架、了解SpringCloud微服务 2、&nbsp;熟悉常用项目管理工具:SVN、GIT、MAVEN、Jenkins 3、&nbsp;熟悉Nginx、tomca...
SpringBoot2.x系列教程(三十六)SpringBoot之Tomcat配置
Spring Boot默认内嵌的Tomcat为Servlet容器,关于Tomcat的所有属性都在ServerProperties配置类中。同时,也可以实现一些接口来自定义内嵌Servlet容器和内嵌Tomcat等的配置。 关于此配置,网络上有大量的资料,但都是基于SpringBoot1.5.x版本,并不适合当前最新版本。本文将带大家了解一下最新版本的使用。 ServerProperties的部分源...
Python绘图,圣诞树,花,爱心 | Turtle篇
每周每日,分享Python实战代码,入门资料,进阶资料,基础语法,爬虫,数据分析,web网站,机器学习,深度学习等等。 公众号回复【进群】沟通交流吧,QQ扫码进群学习吧 微信群 QQ群 1.画圣诞树 import turtle screen = turtle.Screen() screen.setup(800,600) circle = turtle.Turtle()...
作为一个程序员,CPU的这些硬核知识你必须会!
CPU对每个程序员来说,是个既熟悉又陌生的东西? 如果你只知道CPU是中央处理器的话,那可能对你并没有什么用,那么作为程序员的我们,必须要搞懂的就是CPU这家伙是如何运行的,尤其要搞懂它里面的寄存器是怎么一回事,因为这将让你从底层明白程序的运行机制。 随我一起,来好好认识下CPU这货吧 把CPU掰开来看 对于CPU来说,我们首先就要搞明白它是怎么回事,也就是它的内部构造,当然,CPU那么牛的一个东...
破14亿,Python分析我国存在哪些人口危机!
一、背景 二、爬取数据 三、数据分析 1、总人口 2、男女人口比例 3、人口城镇化 4、人口增长率 5、人口老化(抚养比) 6、各省人口 7、世界人口 四、遇到的问题 遇到的问题 1、数据分页,需要获取从1949-2018年数据,观察到有近20年参数:LAST20,由此推测获取近70年的参数可设置为:LAST70 2、2019年数据没有放上去,可以手动添加上去 3、将数据进行 行列转换 4、列名...
听说想当黑客的都玩过这个Monyer游戏(1~14攻略)
第零关 进入传送门开始第0关(游戏链接) 请点击链接进入第1关: 连接在左边→ ←连接在右边 看不到啊。。。。(只能看到一堆大佬做完的留名,也能看到菜鸡的我,在后面~~) 直接fn+f12吧 &lt;span&gt;连接在左边→&lt;/span&gt; &lt;a href="first.php"&gt;&lt;/a&gt; &lt;span&gt;←连接在右边&lt;/span&gt; o...
在家远程办公效率低?那你一定要收好这个「在家办公」神器!
相信大家都已经收到国务院延长春节假期的消息,接下来,在家远程办公可能将会持续一段时间。 但是问题来了。远程办公不是人在电脑前就当坐班了,相反,对于沟通效率,文件协作,以及信息安全都有着极高的要求。有着非常多的挑战,比如: 1在异地互相不见面的会议上,如何提高沟通效率? 2文件之间的来往反馈如何做到及时性?如何保证信息安全? 3如何规划安排每天工作,以及如何进行成果验收? ...... ...
作为一个程序员,内存和磁盘的这些事情,你不得不知道啊!!!
截止目前,我已经分享了如下几篇文章: 一个程序在计算机中是如何运行的?超级干货!!! 作为一个程序员,CPU的这些硬核知识你必须会! 作为一个程序员,内存的这些硬核知识你必须懂! 这些知识可以说是我们之前都不太重视的基础知识,可能大家在上大学的时候都学习过了,但是嘞,当时由于老师讲解的没那么有趣,又加上这些知识本身就比较枯燥,所以嘞,大家当初几乎等于没学。 再说啦,学习这些,也看不出来有什么用啊!...
这个世界上人真的分三六九等,你信吗?
偶然间,在知乎上看到一个问题 一时间,勾起了我深深的回忆。 以前在厂里打过两次工,做过家教,干过辅导班,做过中介。零下几度的晚上,贴过广告,满脸、满手地长冻疮。 再回首那段岁月,虽然苦,但让我学会了坚持和忍耐。让我明白了,在这个世界上,无论环境多么的恶劣,只要心存希望,星星之火,亦可燎原。 下文是原回答,希望能对你能有所启发。 如果我说,这个世界上人真的分三六九等,...
2020年全新Java学习路线图,含配套视频,学完即为中级Java程序员!!
新的一年来临,突如其来的疫情打破了平静的生活! 在家的你是否很无聊,如果无聊就来学习吧! 世上只有一种投资只赚不赔,那就是学习!!! 传智播客于2020年升级了Java学习线路图,硬核升级,免费放送! 学完你就是中级程序员,能更快一步找到工作! 一、Java基础 JavaSE基础是Java中级程序员的起点,是帮助你从小白到懂得编程的必经之路。 在Java基础板块中有6个子模块的学...
B 站上有哪些很好的学习资源?
哇说起B站,在小九眼里就是宝藏般的存在,放年假宅在家时一天刷6、7个小时不在话下,更别提今年的跨年晚会,我简直是跪着看完的!! 最早大家聚在在B站是为了追番,再后来我在上面刷欧美新歌和漂亮小姐姐的舞蹈视频,最近两年我和周围的朋友们已经把B站当作学习教室了,而且学习成本还免费,真是个励志的好平台ヽ(.◕ฺˇд ˇ◕ฺ;)ノ 下面我们就来盘点一下B站上优质的学习资源: 综合类 Oeasy: 综合...
爬取薅羊毛网站百度云资源
这是疫情期间无聊做的爬虫, 去获取暂时用不上的教程 import threading import time import pandas as pd import requests import re from threading import Thread, Lock # import urllib.request as request # req=urllib.request.Requ...
如何优雅地打印一个Java对象?
你好呀,我是沉默王二,一个和黄家驹一样身高,和刘德华一样颜值的程序员。虽然已经写了十多年的 Java 代码,但仍然觉得自己是个菜鸟(请允许我惭愧一下)。 在一个月黑风高的夜晚,我思前想后,觉得再也不能这么蹉跎下去了。于是痛下决心,准备通过输出的方式倒逼输入,以此来修炼自己的内功,从而进阶成为一名真正意义上的大神。与此同时,希望这些文章能够帮助到更多的读者,让大家在学习的路上不再寂寞、空虚和冷。 ...
雷火神山直播超两亿,Web播放器事件监听是怎么实现的?
Web播放器解决了在手机浏览器和PC浏览器上播放音视频数据的问题,让视音频内容可以不依赖用户安装App,就能进行播放以及在社交平台进行传播。在视频业务大数据平台中,播放数据的统计分析非常重要,所以Web播放器在使用过程中,需要对其内部的数据进行收集并上报至服务端,此时,就需要对发生在其内部的一些播放行为进行事件监听。 那么Web播放器事件监听是怎么实现的呢? 01 监听事件明细表 名...
3万字总结,Mysql优化之精髓
本文知识点较多,篇幅较长,请耐心学习 MySQL已经成为时下关系型数据库产品的中坚力量,备受互联网大厂的青睐,出门面试想进BAT,想拿高工资,不会点MySQL优化知识,拿offer的成功率会大大下降。 为什么要优化 系统的吞吐量瓶颈往往出现在数据库的访问速度上 随着应用程序的运行,数据库的中的数据会越来越多,处理时间会相应变慢 数据是存放在磁盘上的,读写速度无法和内存相比 如何优化 设计...
HTML5适合的情人节礼物有纪念日期功能
前言 利用HTML5,css,js实现爱心树 以及 纪念日期的功能 网页有播放音乐功能 以及打字倾诉感情的画面,非常适合情人节送给女朋友 具体的HTML代码 具体只要修改代码里面的男某某和女某某 文字段也可自行修改,还有代码下半部分的JS代码需要修改一下起始日期 注意月份为0~11月 也就是月份需要减一。 当然只有一部分HTML和JS代码不够运行的,文章最下面还附加了完整代码的下载地址 &lt;!...
相关热词 c# 时间比天数 c# oracle查询 c# 主动推送 事件 c# java 属性 c# 控制台 窗体 c# 静态类存值 c#矢量作图 c#窗体调用外部程式 c# enum是否合法 c# 如何卸载引用
立即提问