springmvc中DAO中save方法与数据库

save方法:
public void save(T o){

    getSession().save(o);

}

controller里的方法:
@RequestMapping(value = "/fileUpload2.do", method = RequestMethod.POST)

public String fileUpload2(Long id,Video video,ModelMap map,HttpServletRequest request)

throws IllegalStateException, IOException {

System.out.println("id是"+id);
// 设置上下方文

CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(

request.getSession().getServletContext());
System.out.println("2");
// 检查form是否有enctype="multipart/form-data"

if (multipartResolver.isMultipart(request)) {

MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

System.out.println("3");
Iterator iter = multiRequest.getFileNames();

while (iter.hasNext()) {

// 由CommonsMultipartFile继承而来,拥有上面的方法.

MultipartFile file = multiRequest.getFile(iter.next());

if (file != null) {

String videoname = "Upload" + file.getOriginalFilename();
video.setvideoname(videoname);
String path = "E:/" + videoname;

video.setPath(path);
File localFile = new File(path);

file.transferTo(localFile);
System.out.println("4");
}

}

}
Long Tid=id;
map.addAttribute("id", id);
map.addAttribute("Tid", Tid);
video.setTid(Tid);
System.out.println("视频路径是1"+video.getPath());
System.out.println("视频Tid是1"+video.getTid());
videoService.save(video);
System.out.println("视频路径是2"+video.getPath());
System.out.println("视频Tid是2"+video.getTid());
return "main/homework";

}

控制台打印信息是正确的,但是数据库中没有插入相应信息。有木有大神指点?挺急的,在线等。

4个回答

dao层代码呢?你怎么插进去的啊?不会是走了 getSession().save(o);

这个吧?这个不是插数据库的啊,你点进去看看这个save方法是实现什么的

u013234356
不常发疯的疯子 我解决啦,嘿嘿
大约 5 年之前 回复
u013234356
不常发疯的疯子 那应该是什么
大约 5 年之前 回复
lidongming19890916
lidongming19890916 这个不是插数据库
大约 5 年之前 回复
u013234356
不常发疯的疯子 那个save方法就是dao层的,save不是添加新数据的吗?
大约 5 年之前 回复

数据库相关的配置中有没有设置自动提交呢,如果没有的话,还需要在save操作后面添加commit操作的。

这个不是插数据库.可以看看其他

这个不是插数据库.可以看看其他

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于Springmvc数据库插入的问题

现在遇到一个很奇怪的问题。我的dao和service都有一个基础类 里面定义了增加和查询的方法 然后我两个表的dao和service都去继承这个类。User表可以正常的添加和查询。另一个表只能查询不能添加。。也不会报错。。求解为什么会这样。。 以下是基础DAO类的插入代码 public PK save(T entity) { Assert.notNull(entity, "entity is required"); getSession().save(entity); getSession().close(); return (PK) getSession().save(entity); }

在service层里调用了dao的两个方法,如何保证这两个方法执行在同一个事务中呢?

service里有如下方法 Java code@Transactional(rollbackFor = Exception.class) public boolean del(Integer id) { boolean b = false; b = backDao.del(id); Back bs = new Back(); bs.setUserName(null); backDao.save(bs); return b; } 我想实现的是只用当删除和保存都正确的情况下,才持久化到数据库中去,现在我调用这个del方法时,保存明显是错误的,插入不到数据库中去,而且后台也报错了,但是还是可以删除操作的 dao中方法如下,继承了SqlMapClientDaoSupport Java codepublic boolean delete(final String sqlId, final PK pk) { boolean flag = false; try { this.getSqlMapClientTemplate().delete(sqlId, pk); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public boolean save(final String sqlId, final T entity) { boolean flag = false; try { this.getSqlMapClientTemplate().insert(sqlId, entity); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } 还有一个问题,怎么能保证save,del等方法正确执行呢,我是用返回一个boolean型来判断的,如果抛异常就说明没有成功执行,但是我感觉不太好

SpringMVC结构有没有可能在不基于XML的方式中与数据库发生交互?

小弟之前使用Sping框架的时候SQL语言都是写在XML中的,如: ``` <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="com.sdzw.dao.AdminsMapper"> <!-- findAdminName --> <!-- 根据传入的adminname查找相关的信息 --> <select id="findAdminName" parameterType="java.lang.String" resultType="com.sdzw.entity.Admins"> SELECT * FROM admins WHERE admin_name= #{adminName} </select> <!-- save --> <!-- 保存新建的管理员账户 --> <insert id="save" parameterType="com.sdzw.entity.Admins"> INSERT INTO admins VALUES (#{admin_id},#{admin_name}, #{admin_password},#{admin_nickname}) </insert> <!-- update --> <!-- 对已经存在的用户信息进行修改 --> <update id="update" parameterType="com.sdzw.entity.Admins"> UPDATE admins SET admin_name=#{admin_name},admin_password=#{admin_password},admin_nickname=#{admin_nickname} WHERE admin_id=#{admin_id} </update> </mapper> ``` 现在领导要求将代码写死在Java语言中,还要使用Spring框架,请问有没有解决的办法

SpringMvc 事务无法回滚

我模拟了一个更新和添加操作,添加一个主键重复的用户。按理说添加失败,更新就要回滚。但是事务无法回滚。网上找了好多资料,大部分都是说扫描包时applicationContext.xml和spring-mvc.xml,中包不要重复扫描,排除spring-mvc.xml扫描的Service。但是我怎么改,事务依旧无法回滚,希望大哥们帮帮我这个新手。代码如下 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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:annotation-config/> <context:component-scan base-package="com.ali.zyh"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:properties/jdbc.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> <property name="driverClassName" value="${driverClass}"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mapperLocations" value="classpath:mapping/*.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ali.zyh.dao"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" read-only="false" /> <tx:method name="delete*" propagation="REQUIRED" read-only="false" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" /> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> <tx:annotation-driven transaction-manager="transactionManager"/> <aop:config> <aop:pointcut id="pc" expression="execution(* com.ali.zyh.service.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pc"/> </aop:config> </beans> ``` spring-mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:annotation-config/> <context:component-scan base-package="com.ali.zyh" > <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> </context:component-scan> <mvc:annotation-driven /> <!--避免IE执行AJAX时,返回JSON出现下载文件 --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json</value> </list> </property> <property name="features"> <list> <value>WriteMapNullValue</value> <value>QuoteFieldNames</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射(适配器) --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> <value>text/plain;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 定义跳转的文件的前后缀 ,视图模式配置 (视图渲染器)--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/webapp/jsp"/> <property name="suffix" value=".jsp"/> </bean> <!-- 文件上传配置 --> <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver"> <!--默认编码--> <property name="defaultEncoding" value="UTF-8"/> <!--上传文件的大小限制--> <property name="maxUploadSize" value="32505856"/> <!--内存中的最大值--> <property name="maxInMemorySize" value="4096"/> </bean> </beans> ``` web.xml ``` <web-app> <display-name>zyh</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring/applicationContext.xml</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:/properties/log4j.properties</param-value> </context-param> <listener>      <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  </listener> <servlet> <servlet-name>SpringMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--contextConfigLocation配置springMvc的配置文件(也就是适配器,映射器)--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>SpringMvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> ``` Service层代码 ``` @Service public class UsersService { @Autowired UsersDao usersDao; public void addUsers(Users users) { usersDao.addUsers(users); } public void deleteUsers(String id) { usersDao.deleteUsers(id); } public void updateUsers(Users users) { usersDao.updateUsers(users); } public Users getUsers(String id) { return usersDao.getUsers(id); } } ``` Controller代码 ``` @ResponseBody @RequestMapping(value = "/getOrders",method = RequestMethod.GET) public Object getOrders(String user_id){ Users u = usersService.getUsers(user_id); u.setUsername("aaa"); Users users = new Users(); users.setId("2222"); users.setUsername("事务大哥我错了"); users.setPassword("1111111123"); usersService.updateUsers(u); usersService.addUsers(users); return Msg.OK(); } ```

多数据源springmvc+hibernate 切换问题 在一次请求中多次切换不成功

最近写了一个多数据源的代码,结果在使用的过程中出现了在一个请求中(方法中)两个数据库交替使用的情况,最后情况是数据库切换不过来 并且在项目配置中有懒加载和OpenSessionInViewFilter 数据库一个为本地数据库一个为基金数据库 要做的事情就是在本地查询到基金代码接着再循环去基金库查询基金数据 中间报错为在本地数据库中查询不到某个表(其实是在基金库中) controller层 ``` @RequestMapping(value = "/fundsmatch") public String fundsMatch(HttpServletRequest request, HttpServletResponse response){ BtnHitsCount hits = olService.findByBtnNameAndPage("匹配理财方案", "我的页面"); hits.setHits(hits.getHits()+1); olService.saveHits(hits); if (getAttributeFromSession(Constant.SESSION_KEY_CURRENTUSERID) == null) { return "login"; } String openuid = "c8572f0f-dca3-4b63-aecd-2f32d5510ba3"; Integer userId = (Integer)getAttributeFromSession(Constant.SESSION_KEY_CURRENTUSERID); -------------------在本地库取数据-------------------- JoUser joUser = joUserService.find(userId); PortfolioMatch match = portfolioMatchService.findEntity(userId+""); List<FundsGroupBean> list = new ArrayList<FundsGroupBean>(); if(joUser.getRisklevel()!=null&&match!=null&&match.getPlanId()!=null){ ScoreStandard standard = scoreStandard.findEntity(match.getScoreId()+""); FundPortfolio fundPortfolio = match.getFundPortfolioId(); String[] fundcodes = fundPortfolio.getFundcodes().split(","); for (int i = 0; i < fundcodes.length; i++) { FundsGroupBean fgb = new FundsGroupBean(); try { --------------切换基金库取数据-------------- JSONObject json = JSONObject.fromObject(fundsNavService.findFundsInfo(fundcodes[i])); --------------切换基金库取数据-------------- } catch (Exception e) { e.printStackTrace();--------------在此报错-------------------- } fgb.setFundCode(fundcodes[i]); list.add(fgb); } request.setAttribute("list", list); request.setAttribute("rates", fundPortfolio.getMinIncomeRate()+"~"+fundPortfolio.getMaxIncomeRate()); request.setAttribute("risktest", 1); request.setAttribute("level", joUser.getRisklevel()+" "+standard.getName()); }else{ return "redirect:/questionnaire/plan_questionnaire"; } return "fundsmatch"; } ``` 基金server层内部代码 ``` @Service public class FundsNavServiceImpl implements FundsNavService { @Autowired FundsNavDao dao; public Map<String, Object> findNav(String fundcode, String day) { ContextHolder.setDbType(DBType.dataSource2); Map<String,Object> map = dao.findNav(fundcode, day); ContextHolder.clearDBType(); return map; } public Map<String, Object> findFundsInfo(String fundcode) { ContextHolder.setDbType(DBType.dataSource2); Map<String,Object> retMap = new HashMap<String,Object>(); retMap.put("fundinfo", dao.findFundsInfo(fundcode)); ContextHolder.clearDBType(); return retMap; } public Map<String, Object> searchFunds(String fundcode, String page, String rows) { ContextHolder.setDbType(DBType.dataSource2); Map<String,Object> retMap = new HashMap<String,Object>(); retMap.put("fundList", dao.searchFunds(fundcode, page, rows)); ContextHolder.clearDBType(); return retMap; } } ``` 数据源枚举类 ``` package com.chy.dangaowm.util.fund; public enum DBType { dataSource1, dataSource2 } ``` 继承的AbstractRoutingDataSource类并且在spring中配置 ``` package com.chy.dangaowm.util.fund; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { DBType dbType = ContextHolder.getDBType(); return dbType; } } ``` 基金库切换类 ``` package com.chy.dangaowm.util.fund; public class ContextHolder { private static final ThreadLocal<Object> holder = new ThreadLocal<Object>(); public static void setDbType(DBType dbType){ holder.set(dbType); } public static DBType getDBType(){ return (DBType)holder.get(); } public static void clearDBType(){ holder.remove(); } } ``` spring配置文件 ``` <!-- 配置dataSource1 进行save,update操作时连接这个数据库--> <bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.slave.url}" /> <property name="username" value="${jdbc.slave.username}" /> <property name="password" value="${jdbc.slave.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxIdle" value="${jdbc.maxIdle}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="testOnBorrow" value="${jdbc.testOnBorrow}" /> <property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> <property name="validationQuery" value="${jdbc.validationQuery}" /> <!-- <property name="validationQuery" value="select 1;" /> --> </bean> <!--配置dataSource1 进行select操作时连接这个数据库 --> <bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.master.url}" /> <property name="username" value="${jdbc.master.username}" /> <property name="password" value="${jdbc.master.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxIdle" value="${jdbc.maxIdle}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="testOnBorrow" value="${jdbc.testOnBorrow}" /> <property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> <property name="validationQuery" value="${jdbc.validationQuery}" /> <!-- <property name="validationQuery" value="select 1;" /> --> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource1" /> <!-- mysql 动态数据源设置--> <bean id="mysqlDynamicDataSource" class="com.chy.dangaowm.util.fund.DynamicDataSource"> <property name="targetDataSources"> <!-- 标识符类型 --> <map key-type="com.chy.dangaowm.util.fund.DBType"> <entry key="dataSource1" value-ref="dataSource1"/> <entry key="dataSource2" value-ref="dataSource2"/> </map> </property> <property name="defaultTargetDataSource" ref="dataSource1"/> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="mysqlDynamicDataSource" /> <property name="namingStrategy"> <bean class="org.hibernate.cfg.ImprovedNamingStrategy" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> </props> </property> <property name="packagesToScan"> <array> <value>com.chy.dangaowm.domain</value> </array> </property> </bean> <!-- 配置事务管理 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> ```

springMVC spring3.1 hibernate4 cxf整合发布restful风格的webservice

<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>现在的问题是通过controller访问service是正常的,用cxf发布的webservice  就不访问不了service,报错:</p> <p><span style="color: #ff0000;">org.apache.cxf.interceptor.Fault: No Session found for current thread</span></p> <p>at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:162)</p> <p>at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:128)</p> <p>at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:167)</p> <p>at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:94)</p> <p>at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58)</p> <p>at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:94)</p> <p>at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:262)</p> <p>at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)</p> <p>at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:211)</p> <p>at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:213)</p> <p>at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:154)</p> <p>at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:130)</p> <p>at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:221)</p> <p>at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doGet(AbstractHTTPServlet.java:146)</p> <p>at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)</p> <p>at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:197)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)</p> <p>at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)</p> <p>at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)</p> <p>at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)</p> <p>at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)</p> <p>at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)</p> <p>at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)</p> <p>at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)</p> <p>at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)</p> <p>at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)</p> <p>at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)</p> <p>at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)</p> <p>at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)</p> <p>at java.lang.Thread.run(Thread.java:662)</p> <p><span style="color: #ff0000;">Caused by: org.hibernate.HibernateException: No Session found for current thread</span></p> <p>at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)</p> <p>at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:941)</p> <p>at com.tservice.gisnavi.dao.impl.BaseDaoImpl.getCurrentSession(BaseDaoImpl.java:152)</p> <p>at com.tservice.gisnavi.dao.impl.BaseDaoImpl.find(BaseDaoImpl.java:186)</p> <p>at com.tservice.gisnavi.service.impl.RoutingCalculationServiceImpl.find(RoutingCalculationServiceImpl.java:14)</p> <p>at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)</p> <p>at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)</p> <p>--------------------------------------------------------------------------------------------------------------------------------------------------------------------</p> <p>spring-hibernate.xml配置:</p> <p>&lt;!-- 配置数据源 --&gt;</p> <p>&lt;bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"&gt;</p> <p>&lt;property name="url" value="${jdbc_url}" /&gt;</p> <p>&lt;property name="username" value="${jdbc_username}" /&gt;</p> <p>&lt;property name="password" value="${jdbc_password}" /&gt;</p> <p> </p> <p>&lt;!-- 初始化连接大小 --&gt;</p> <p>&lt;property name="initialSize" value="0" /&gt;</p> <p>&lt;!-- 连接池最大使用连接数量 --&gt;</p> <p>&lt;property name="maxActive" value="20" /&gt;</p> <p>&lt;!-- 连接池最大空闲 --&gt;</p> <p>&lt;property name="maxIdle" value="20" /&gt;</p> <p>&lt;!-- 连接池最小空闲 --&gt;</p> <p>&lt;property name="minIdle" value="0" /&gt;</p> <p>&lt;!-- 获取连接最大等待时间 --&gt;</p> <p>&lt;property name="maxWait" value="60000" /&gt;</p> <p> </p> <p>&lt;!-- &lt;property name="poolPreparedStatements" value="true" /&gt; &lt;property name="maxPoolPreparedStatementPerConnectionSize" value="33" /&gt; --&gt;</p> <p> </p> <p>&lt;property name="validationQuery" value="${validationQuery}" /&gt;</p> <p>&lt;property name="testOnBorrow" value="false" /&gt;</p> <p>&lt;property name="testOnReturn" value="false" /&gt;</p> <p>&lt;property name="testWhileIdle" value="true" /&gt;</p> <p> </p> <p>&lt;!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --&gt;</p> <p>&lt;property name="timeBetweenEvictionRunsMillis" value="60000" /&gt;</p> <p>&lt;!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --&gt;</p> <p>&lt;property name="minEvictableIdleTimeMillis" value="25200000" /&gt;</p> <p> </p> <p>&lt;!-- 打开removeAbandoned功能 --&gt;</p> <p>&lt;property name="removeAbandoned" value="true" /&gt;</p> <p>&lt;!-- 1800秒,也就是30分钟 --&gt;</p> <p>&lt;property name="removeAbandonedTimeout" value="1800" /&gt;</p> <p>&lt;!-- 关闭abanded连接时输出错误日志 --&gt;</p> <p>&lt;property name="logAbandoned" value="true" /&gt;</p> <p> </p> <p>&lt;!-- 监控数据库 --&gt;</p> <p>&lt;!-- &lt;property name="filters" value="stat" /&gt; --&gt;</p> <p>&lt;property name="filters" value="mergeStat" /&gt;</p> <p>&lt;/bean&gt;</p> <p> </p> <p>&lt;!-- 配置hibernate session工厂 --&gt;</p> <p>&lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;</p> <p>&lt;property name="dataSource" ref="dataSource" /&gt;</p> <p>&lt;property name="hibernateProperties"&gt;</p> <p>&lt;props&gt;</p> <p>&lt;prop key="hibernate.hbm2ddl.auto"&gt;${hibernate.hbm2ddl.auto}&lt;/prop&gt;</p> <p>&lt;prop key="hibernate.dialect"&gt;${hibernate.dialect}&lt;/prop&gt;</p> <p>&lt;prop key="hibernate.show_sql"&gt;${hibernate.show_sql}&lt;/prop&gt;</p> <p>&lt;prop key="hibernate.format_sql"&gt;${hibernate.format_sql}&lt;/prop&gt;</p> <p>&lt;/props&gt;</p> <p>&lt;/property&gt;</p> <p> </p> <p>&lt;!-- 自动扫描注解方式配置的hibernate类文件 --&gt;</p> <p>&lt;property name="packagesToScan"&gt;</p> <p>&lt;list&gt;</p> <p>&lt;value&gt;com.tservice.gisnavi&lt;/value&gt;</p> <p>&lt;/list&gt;</p> <p>&lt;/property&gt;</p> <p> </p> <p>&lt;!-- 自动扫描hbm方式配置的hibernate文件和.hbm文件 --&gt;</p> <p>&lt;!-- </p> <p>&lt;property name="mappingDirectoryLocations"&gt;</p> <p>&lt;list&gt;</p> <p>&lt;value&gt;classpath:sy/hbm&lt;/value&gt;</p> <p>&lt;/list&gt;</p> <p>&lt;/property&gt;</p> <p>--&gt;</p> <p>&lt;/bean&gt;</p> <p> </p> <p>&lt;!-- 配置事务管理器 --&gt;</p> <p>&lt;bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;</p> <p>&lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt;</p> <p>&lt;/bean&gt;</p> <p> </p> <p>&lt;!-- &lt;aop:aspectj-autoproxy expose-proxy="true"/&gt; --&gt;</p> <p> </p> <p>&lt;!-- 注解方式配置事物 --&gt;</p> <p>&lt;!-- &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; --&gt;</p> <p> </p> <p>&lt;!-- 拦截器方式配置事物 --&gt;</p> <p>&lt;tx:advice id="transactionAdvice" transaction-manager="transactionManager"&gt;</p> <p>&lt;tx:attributes&gt;</p> <p>&lt;tx:method name="add*" /&gt;</p> <p>&lt;tx:method name="save*" /&gt;</p> <p>&lt;tx:method name="update*" /&gt;</p> <p>&lt;tx:method name="modify*" /&gt;</p> <p>&lt;tx:method name="edit*" /&gt;</p> <p>&lt;tx:method name="delete*" /&gt;</p> <p>&lt;tx:method name="remove*" /&gt;</p> <p>&lt;tx:method name="repair" /&gt;</p> <p>&lt;tx:method name="deleteAndRepair" /&gt;</p> <p> </p> <p>&lt;tx:method name="get*" read-only="true" propagation="SUPPORTS" /&gt;</p> <p>&lt;tx:method name="find*" read-only="true" propagation="SUPPORTS" /&gt;</p> <p>&lt;tx:method name="load*" read-only="true" propagation="SUPPORTS" /&gt;</p> <p>&lt;tx:method name="search*" read-only="true" propagation="SUPPORTS" /&gt;</p> <p>&lt;tx:method name="datagrid*" propagation="SUPPORTS" /&gt;</p> <p> </p> <p>&lt;tx:method name="*" propagation="SUPPORTS" /&gt;</p> <p>&lt;/tx:attributes&gt;</p> <p>&lt;/tx:advice&gt;</p> <p> </p> <p>&lt;aop:config&gt;</p> <p>&lt;aop:pointcut id="transactionPointcut" expression="execution(* com.tservice.gisnavi.service..*.*(..))" /&gt;</p> <p>&lt;aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /&gt;</p> <p>&lt;/aop:config&gt;</p> <p> </p> <p>&lt;/beans&gt;</p> <p> </p> <p> </p> <p> </p> </div>

hibernate 不用事务,也提交到了数据库,帮忙看看

<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>配置 spring mvc + hibernate , 我在配置文件配置了注解的事务,但是<span style="color: #ff0000;">controller 没写上@transaction 数据竟然插入到了数据库, 我都把事务的配置文件给干掉了也是提交到了数据库</span>, 看了半天找不到, 帮忙看看,谢谢! 用的是sql server 数据库</p> <p> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;WEB-INF/spring/spring.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;!-- 配置DispatcherServlet--&gt; &lt;servlet&gt; &lt;servlet-name&gt;springMVC&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;WEB-INF/spring/springMVC.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;springMVC&lt;/servlet-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;!-- 监听器 --&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;!-- 编码过滤器 --&gt; &lt;filter&gt; &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.CharacterEncodingFilter&lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;encoding&lt;/param-name&gt; &lt;param-value&gt;UTF-8&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- security --&gt; &lt;filter&gt; &lt;filter-name&gt;springSecurityFilterChain&lt;/filter-name&gt; &lt;filter-class&gt;org.springframework.web.filter.DelegatingFilterProxy&lt;/filter-class&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;springSecurityFilterChain&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.do&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt;</pre> <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:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"&gt; &lt;context:annotation-config /&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.belief.web.controller.**"&gt;&lt;/context:component-scan&gt; &lt;bean id="springContextUtil" class="com.belief.web.common.util.SpringContextUtil" &gt;&lt;/bean&gt; &lt;bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"&gt; &lt;property name="basename"&gt; &lt;value&gt;/WEB-INF/message/message&lt;/value&gt; &lt;/property&gt; &lt;property name="cacheSeconds"&gt; &lt;value&gt;-1&lt;/value&gt; &lt;/property&gt; &lt;property name="defaultEncoding"&gt; &lt;value&gt;UTF-8&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- 默认的注解 --&gt; &lt;!-- &lt;mvc:annotation-driven/&gt; --&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"&gt; &lt;!-- &lt;property name="interceptors"&gt; &lt;list&gt; &lt;bean class="com.belief.web.common.MyIntercepter"&gt;&lt;/bean&gt; 国际化拦截器配置 &lt;bean id="localResolver" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"&gt;&lt;/bean&gt; &lt;/list&gt; &lt;/property&gt; --&gt; &lt;/bean&gt; &lt;!-- 手动注册注解 --&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;property name="messageConverters"&gt; &lt;list&gt; &lt;ref bean="byteArray_hmc" /&gt; &lt;ref bean="string_hmc" /&gt; &lt;ref bean="resource_hmc" /&gt; &lt;ref bean="source_hmc" /&gt; &lt;ref bean="xmlAware_hmc" /&gt; &lt;ref bean="jaxb2Root-hmc" /&gt; &lt;ref bean="jackson_hmc" /&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="byteArray_hmc" class="org.springframework.http.converter.ByteArrayHttpMessageConverter"&gt;&lt;/bean&gt; &lt;bean id="string_hmc" class="org.springframework.http.converter.StringHttpMessageConverter"&gt; &lt;property name ="supportedMediaTypes"&gt; &lt;list&gt;&lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;&lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="resource_hmc" class="org.springframework.http.converter.ResourceHttpMessageConverter"&gt;&lt;/bean&gt; &lt;bean id="source_hmc" class="org.springframework.http.converter.xml.SourceHttpMessageConverter"&gt;&lt;/bean&gt; &lt;bean id="xmlAware_hmc" class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"&gt;&lt;/bean&gt; &lt;bean id="jaxb2Root-hmc" class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"&gt;&lt;/bean&gt; &lt;bean id="jackson_hmc" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"&gt;&lt;/bean&gt; &lt;!-- 试图解析 --&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/pages/" &gt; &lt;!-- &lt;property name="prefix" value="/WEB-INF/pages/"&gt;&lt;/property&gt; &lt;property name="suffix" value=""&gt;&lt;/property&gt; --&gt; &lt;property name="viewClass" value="org.springframework.web.servlet.view.JstlView"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver"&gt; &lt;property name="cookieName" value="clientlanguage"/&gt; &lt;property name="cookieMaxAge"&gt; &lt;value&gt;2592000&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- 拦截器 --&gt; &lt;mvc:interceptors&gt; &lt;bean class="com.belief.web.common.intercepter.MyIntercepter"&gt;&lt;/bean&gt; &lt;!-- 国际化拦截器配置 --&gt; &lt;bean id="localResolver" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"&gt;&lt;/bean&gt; &lt;!-- 单独URL配置拦截器 --&gt; &lt;!-- &lt;mvc:interceptor&gt; &lt;mvc:mapping path="/user/*" /&gt; &lt;bean class="com.belief.web.common.MyIntercepter"&gt;&lt;/bean&gt; &lt;/mvc:interceptor&gt; --&gt; &lt;/mvc:interceptors&gt; &lt;!-- 静态资源文件的访问,方案一 --&gt; &lt;mvc:default-servlet-handler/&gt; &lt;!-- 静态资源文件的访问,方案二 cache-period 可以使得静态资源进行web cache --&gt; &lt;!-- &lt;mvc:resources location="/images/" mapping="/images/**" cache-period="31556926" /&gt; &lt;mvc:resources location="/js/" mapping="/js/**"/&gt; &lt;mvc:resources location="/css/" mapping="/css/**"/&gt; --&gt; &lt;!-- 全局异常处理 --&gt; &lt;bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"&gt; &lt;property name="defaultErrorView"&gt; &lt;value&gt;/error/exception.jsp&lt;/value&gt; &lt;/property&gt; &lt;!-- 值:“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”,是“SimpleMappingExceptionResolver类的全限定名”。 这个值不是随便写的。 因为我在log4j的配置文件中还要加入 log4j.logger.org.springframework.web.servlet.handler.SimpleMappingExceptionResolver=WARN, 保证这个级别是warn的日志一定会被记录,即使log4j的根日志级别是ERROR。 --&gt; &lt;property name="warnLogCategory"&gt; &lt;value&gt;org.springframework.web.servlet.handler.SimpleMappingExceptionResolver&lt;/value&gt; &lt;/property&gt; &lt;property name="exceptionMappings"&gt; &lt;props&gt; &lt;prop key="java.lang.IllegalArgumentException"&gt;/error/exception.jsp&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans default-autowire="byName" 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" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"&gt; &lt;bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource" depends-on="propertyConfigurer"&gt; &lt;property name="driver" value="${jdbc.driverClassName}"&gt;&lt;/property&gt; &lt;property name="driverUrl" value="${jdbc.url}"&gt;&lt;/property&gt; &lt;property name="user" value="${jdbc.username}"&gt;&lt;/property&gt; &lt;property name="password" value="${jdbc.password}"&gt;&lt;/property&gt; &lt;!-- 最大连接数(默认5个) --&gt; &lt;property name="maximumConnectionCount"&gt; &lt;value&gt;60&lt;/value&gt; &lt;/property&gt; &lt;!-- 最小连接数(默认2个) --&gt; &lt;property name="minimumConnectionCount"&gt; &lt;value&gt;10&lt;/value&gt; &lt;/property&gt; &lt;!-- 同时构建节流 --&gt; &lt;property name="simultaneousBuildThrottle"&gt; &lt;value&gt;10000&lt;/value&gt; &lt;/property&gt; &lt;!-- 最少保持的空闲连接数(默认2个) --&gt; &lt;property name="prototypeCount"&gt; &lt;value&gt;5&lt;/value&gt; &lt;/property&gt; &lt;!-- 使用前测试 --&gt; &lt;property name="testBeforeUse"&gt; &lt;value&gt;true&lt;/value&gt; &lt;/property&gt; &lt;!-- 测试使用的sql --&gt; &lt;property name="houseKeepingTestSql"&gt; &lt;value&gt;select getDate()&lt;/value&gt; &lt;/property&gt; &lt;!-- 最大活动时间(超过此时间线程将被kill,默认5分钟) --&gt; &lt;property name="maximumActiveTime"&gt; &lt;value&gt;7200000&lt;/value&gt; &lt;/property&gt; &lt;!-- proxool自动侦察各个连接状态的时间间隔(毫秒),侦察到空闲的连接就马上回收,超时的销毁 默认30秒) --&gt; &lt;!-- &lt;property name="houseKeepingSleepTime" value="${proxool.hourseKeepingSleepTime}"/&gt; --&gt; &lt;/bean&gt; &lt;!-- 可以在XML配置文件中加入外部属性文件 --&gt; &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="location"&gt; &lt;value&gt;WEB-INF/config.properties&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" depends-on="propertyConfigurer"&gt; &lt;property name="dataSource"&gt; &lt;ref local="dataSource" /&gt; &lt;/property&gt; &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt;com/belief/web/biz/user/User.hbm.xml&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;!-- Oracle --&gt; &lt;!-- &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.OracleDialect&lt;/prop&gt; --&gt; &lt;!-- Sql Server --&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.SQLServerDialect&lt;/prop&gt; &lt;prop key="hibernate.cglib.use_reflection_optimizer"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;${hibernate.show_sql}&lt;/prop&gt; &lt;prop key="hibernate.query.substitutions"&gt;true 1, false 0&lt;/prop&gt; &lt;!-- 开启二级缓存 --&gt; &lt;!-- &lt;prop key="hibernate.cache.use_second_level_cache"&gt;true&lt;/prop&gt; --&gt; &lt;!-- 设置缓存类 --&gt; &lt;!-- &lt;prop key="hibernate.cache.provider_class"&gt;org.hibernate.cache.EhCacheProvider&lt;/prop&gt; --&gt; &lt;!-- 否使用结构化的方式缓存对象 --&gt; &lt;!-- &lt;prop key="hibernate.cache.use_structured_entries"&gt;true&lt;/prop&gt; --&gt; &lt;!-- 是否缓存查询结果 --&gt; &lt;!-- &lt;prop key="hibernate.cache.use_query_cache"&gt;true&lt;/prop&gt; --&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"&gt; &lt;property name="sessionFactory"&gt;&lt;ref bean="sessionFactory"/&gt;&lt;/property&gt; &lt;/bean&gt; &lt;!-- 配置事务 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" &gt; &lt;ref local="sessionFactory"/&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- 注解事务 --&gt; &lt;tx:annotation-driven transaction-manager="transactionManager" /&gt; &lt;bean id="dao" class="com.belief.web.common.dao.Dao"&gt; &lt;/bean&gt; &lt;bean id="daoFactorySupport" class="com.belief.web.common.dao.DaoFactorySupport"&gt; &lt;/bean&gt; &lt;/beans&gt;</pre> <p> </p> <pre name="code" class="java">@RequestMapping(value = "/add",method = RequestMethod.POST) public String add(HttpServletRequest request,HttpServletResponse response){ Dao dao = DaoFactory.getInstance().getDao(); User user = new User(); user.setName("hibernate"); user.setState(PojoState.NORMAL); user.setVersion(1); dao.save(user); return "redirect:/index.do"; }</pre> <p> </p> <pre name="code" class="java">public class User extends BaseEntity { private static final long serialVersionUID = 2274719953051444808L; /** 员工姓名 */ private String name; /** 用户组 */ private String userGroup;</pre> <p> </p> <pre name="code" class="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"&gt; &lt;hibernate-mapping&gt; &lt;class name="com.belief.web.biz.user.User" table="auth_user"&gt; &lt;!-- &lt;cache usage="read-write" /&gt; --&gt; &lt;id name="id" column="user_id" unsaved-value="null"&gt; &lt;generator class="identity" /&gt; &lt;/id&gt; &lt;property name="version" column="version" /&gt; &lt;property name="createTime" column="create_time" /&gt; &lt;property name="updateTime" column="update_time" /&gt; &lt;property name="userGroup" column="user_group" /&gt; &lt;property name="penddingReadAnnonAmt" column="pendding_read_annon_amt" /&gt; &lt;many-to-one name="createUser" column="create_user" class="com.belief.web.biz.user.User" /&gt; &lt;many-to-one name="updateUser" column="update_user" class="com.belief.web.biz.user.User" /&gt; &lt;property name="state" type="com.belief.web.common.entity.PojoStateType" /&gt; &lt;property name="name" /&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt;</pre> <p> </p> <pre name="code" class="java">package com.belief.web.common.dao; import java.util.List; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.belief.web.common.entity.BaseEntity; @SuppressWarnings("unchecked") public class Dao extends HibernateDaoSupport{ public &lt;T extends BaseEntity&gt;T get(Class&lt;? extends BaseEntity&gt; cls,String id){ return (T) this.getHibernateTemplate().get(cls, id); } public List&lt;BaseEntity&gt; find(Class&lt;? extends BaseEntity&gt; cls){ return this.getHibernateTemplate().find("FROM "+cls.getName()); } public void save(BaseEntity baseEntity){ getHibernateTemplate().save(baseEntity); } } </pre> <p> </p> <pre name="code" class="java">package com.belief.web.common.dao; public class DaoFactory { private static final DaoFactory instance = new DaoFactory(); public static DaoFactory getInstance() { return instance; } Dao dao; public Dao getDao() { return dao; } } </pre> <p> </p> <pre name="code" class="java">package com.belief.web.common.dao; public class DaoFactorySupport { public void setDao(Dao dao){ DaoFactory.getInstance().dao = dao; } } </pre> <p> </p> </div>

请教:Spring + Hibernate 无法将数据写入数据库?

Spring + Hibernate 无法将数据写入数据 **请教: 通过Junit单元测试Service可以将数据写入数据库;但部署访问却无法向数据库写入数据。** 1 环境: Spring 3.1.2 Hibernate 4.1.4 Jdk1.6 2 配置: 2.1 Web.xml <!-- Spring ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔 此参数用于后面的Spring Context Loader --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--Dispathcer Servlet --> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Spring MVC Servlet 拦截.do结尾的请求--> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--openSessionInView--> <filter> <filter-name>openSessionInView</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>sessionFactoryBeanName</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInView</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 2.2 applicationContext.xml <!--扫描并自动装配 --> <context:annotation-config /> <context:component-scan base-package="com.sp" /> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:application.properties</value> </property> </bean> <!-- 数据源配置 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Connection Pooling Info --> <property name="maxActive" value="${dbcp.maxActive}" /> <property name="maxIdle" value="${dbcp.maxIdle}" /> <property name="defaultAutoCommit" value="false" /> <!-- 连接Idle一个小时后超时 --> <property name="timeBetweenEvictionRunsMillis" value="3600000" /> <property name="minEvictableIdleTimeMillis" value="3600000" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.connection.autocommit">true</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.sp.dao</value> <value>com.sp.entity.dict</value> </list> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" abstract="false" lazy-init="default" autowire="default"> <property name="sessionFactory"><ref bean="sessionFactory" /></property> </bean> <!-- 事务管理配置 --> <!--<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" read-only="false" propagation="REQUIRED" /> <tx:method name="get*" read-only="false" propagation="REQUIRED" /> <tx:method name="add*" read-only="false" propagation="REQUIRED" /> <tx:method name="update*" read-only="false" propagation="REQUIRED" /> <tx:method name="delete*" read-only="false" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <aop:config> <aop:advisor pointcut="execution(* com.sp.service.*.*(..))" advice-ref="txAdvice"/> </aop:config> </beans> 2.3 spring-mvc.xml <!-- 启动注解驱动的SpringMVC功能,注册请求URL和注解POJO类方法的映射 --> <mvc:annotation-driven /> <!-- 自动扫描且只扫描@Controller --> <context:component-scan base-package="com.sp.web" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <context:component-scan base-package="com.sp.dao.impl"></context:component-scan> <context:component-scan base-package="com.sp.service.impl"></context:component-scan> <mvc:default-servlet-handler /> <!-- 对模型视图名称的解析,在请求时模型视图名称添加后缀。定义JSP --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 支持上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> 2.4 hibernate.cfg.xml <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.username">root</property> <property name="connection.password">password</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect <property name="dialect">org.hibernate.dialect.MySQLDialect</property> --> <!-- Enable Hibernate's automatic session context management --> <!-- <property name="current_session_context_class">thread</property> --> <!-- Disable the second-level cache --> <!-- <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>--> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <property name="format_sql">true</property> <!-- Drop and re-create the database schema on startup--> <property name="hbm2ddl.auto">update</property> <property name="javax.persistence.validation.mode">none</property> 3 代码: 3.1 Service层: @Component("userService") public class UserServiceImpl implements UserService{ @Autowired private UserDao userDao; @Autowired private FormValidator validator; @Override public String userLogin(UserModel user) { String password = userDao.userLogin(user); if(password.equals(user.getPassword())){ return "sucess"; }else{ return "false"; } } @Override public List<ProjectType> getAllProjectTypes(){ List<ProjectType> projectType = userDao.getAllProjectTypes(); return projectType; } @Override public String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){ validator.validate(projectType, result); if(result.hasErrors()){ return "newProjectType"; } userDao.save(projectType); //status.setComplete(); return "redirect:showProjectTypes.do"; } //添加《项目类型》 @Override public String addProjectType(ProjectType projectType) { userDao.save(projectType); return "redirect:showProjectTypes.do"; } } 3.2 Control层 @Controller @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @Autowired private FormValidator validator; @RequestMapping(value = "/login",method=RequestMethod.POST) protected String handle(UserModel user,BindingResult result, Model model){ String flag = userService.userLogin(user); System.out.println("flag:" + flag); if ("sucess".equals(flag)){ return "sucess"; } return "test1"; } @RequestMapping(value = "/showProjectTypes") protected ModelAndView getAllProjectTypes(){ ModelAndView mav = new ModelAndView("showProjectTypes"); List<ProjectType> projectTypes = userService.getAllProjectTypes(); mav.addObject("SEARCH_PROJECTTYPE_RESULTS_KEY", projectTypes); return mav; } @RequestMapping(value = "/addProjectType",method=RequestMethod.GET) protected ModelAndView newProjectTypeForm(){ ModelAndView mav = new ModelAndView("newProjectType"); ProjectType projectType = new ProjectType(); mav.getModelMap().put("newProjectType", projectType); return mav; } @RequestMapping(value = "/saveProjectType",method=RequestMethod.POST) protected String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){ //return userService.addProjectType(projectType, result, status); return userService.addProjectType(projectType); } } 3.3 DAO层 @Component("userDao") public class UserDaoImpl implements UserDao{ @Autowired private SessionFactory sessionFactory; public ProjectType getById(int id) { return (ProjectType) sessionFactory.getCurrentSession().get(ProjectType.class, id); } @Override public String userLogin(UserModel user) { return "123456"; } //获取数据 @Override @SuppressWarnings("unchecked") public List<ProjectType> getAllProjectTypes() { Criteria ceriteria = sessionFactory.getCurrentSession().createCriteria(ProjectType.class); return ceriteria.list(); } //新增数据; @Override // @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public int save(ProjectType projectType) { System.out.println("save:---"); System.out.println(projectType.getIndex()); System.out.println(projectType.getProjectType()); System.out.println(projectType.getProjectTypeAbbr()); return (Integer) sessionFactory.getCurrentSession().save(projectType); } }

mybatis insert插入语句以后 一直报错怎么回事 怎么在保存以后获取保存对象的id

项目采用的框架是springmvc mybatis 数据库 mysql 控制器代码: 还有怎么在保存一一张表的同时 保存到另一张表 把A表的id 保存到B表(关联的表) ``` List<EarDiseaseSwtj> listEdSwtj=earStudyService.findEdByid(id1); if (listEdSwtj.size() != 0) { //int num2 = earDisease100Service.updateEdSwtj(id1, name, desc);// 修改的仅是ear_disease_100这个表 int num2=earStudyService.updateEdSwtj(id1, name, desc); if (num2 != 0) { request.setAttribute("ok", "修改成功"); } return "manage/forJsp.do?&requestType=17&num1=" + currentPageNum1; } else { //earStudyService.saveEdSwtj(id1, name, desc); earStudyService.saveEdSwtj(name, desc); request.setAttribute("ok", "添加成功"); return "manage/forJsp.do?&requestType=17&num1=" + currentPageNum1; } } ``` mybatis sql如下: ``` <insert id="saveEd" parameterType="EarDiseaseSwtj"> insert into dt_ear_disease_swtj (name,desc) values (#{name},#{desc}) </insert> ``` 报错代码如下: ``` HTTP Status 500 - Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: type Exception report message Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: description The server encountered an internal error that prevented it from fulfilling this request. exception org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc) values ('qqqe','eqeqe')' at line 2 ### The error may involve com.app.dao.mapper.EarDiseaseSwtjMapper.saveEd-Inline ### The error occurred while setting parameters ### SQL: insert into dt_ear_disease_swtj (name,desc) values (?,?) ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc) values ('qqqe','eqeqe')' at line 2 ; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc) values ('qqqe','eqeqe')' at line 2 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) javax.servlet.http.HttpServlet.service(HttpServlet.java:650) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) root cause org.springframework.jdbc.BadSqlGrammarException: ### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc) values ('qqqe','eqeqe')' at line 2 ### The error may involve com.app.dao.mapper.EarDiseaseSwtjMapper.saveEd-Inline ### The error occurred while setting parameters ### SQL: insert into dt_ear_disease_swtj (name,desc) values (?,?) ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc) values ('qqqe','eqeqe')' at line 2 ; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc) values ('qqqe','eqeqe')' at line 2 org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:233) org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:71) org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:365) sun.proxy.$Proxy10.insert(Unknown Source) org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:237) org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:79) org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:40) sun.proxy.$Proxy39.saveEd(Unknown Source) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) sun.proxy.$Proxy40.saveEd(Unknown Source) com.app.dao.impl.EarDiseaseSwtjDaoImpl.saveEd(Unknown Source) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) sun.proxy.$Proxy41.saveEd(Unknown Source) com.app.service.impl.EarStudyServiceImpl.saveEdSwtj(Unknown Source) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) sun.proxy.$Proxy99.saveEdSwtj(Unknown Source) com.app.totalController.ManageController.forJsp(Unknown Source) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:427) org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:415) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:788) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:717) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560) javax.servlet.http.HttpServlet.service(HttpServlet.java:650) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) root cause ```

Spring+Hibernate 在getCurrentSession的时候报错

以下是我的配置: spring-mvc.xml: ``` <!-- 加载配置文件 --> <context:property-placeholder location="WEB-INF/config/db.config.properties" /> <!-- 自动注入为bean --> <context:component-scan base-package="com.cherry.mall" /> <!-- 启动注解驱动的spring MVC功能,注册请求url和注解POJO类方法的映射 --> <mvc:annotation-driven> <!-- 返回json数据,@response使用 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> <!--这里是对静态资源的映射 --> <!-- <mvc:resources mapping="/js/**" location="/resources/js/" /> <mvc:resources mapping="/css/**" location="/resources/css/" /> <mvc:resources mapping="/img/**" location="/resources/img/" /> --> ``` srping-hibernate: ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"> <!-- 配置数据源 c3p0 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 请求超时时间 --> <property name="checkoutTimeout" value="30000" /> <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 --> <property name="idleConnectionTestPeriod" value="30" /> <!-- 连接数据库连接池最大空闲时间 --> <property name="maxIdleTime" value="30" /> <!-- 连接池初始化连接数 --> <property name="initialPoolSize" value="5" /> <property name="minPoolSize" value="5" /> <property name="maxPoolSize" value="20" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 --> <property name="acquireIncrement" value="5" /> </bean> <!-- 配置hibernate的SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入数据源 相关信息看源码 --> <property name="dataSource" ref="dataSource" /> <!-- hibernate配置信息 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!-- 开启二级缓存 ehcache --> <!-- <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path} </prop> --> </props> </property> <!-- 扫描hibernate注解配置的entity --> <property name="packagesToScan" value="com.cherry.mall.**.model" /> </bean> <!-- mybatis配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="/WEB-INF/config/mybatis-config.xml"></property> <property name="mapperLocations" value="classpath*:com/cherry/mall/**/mapping/*.xml"></property> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置事务增强处理Bean,指定事务管理器 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <!-- 配置详细事务处理语义 --> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="alter*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> <tx:method name="query*" propagation="SUPPORTS" read-only="true" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="select*" propagation="SUPPORTS" read-only="true" /> <tx:method name="load*" propagation="SUPPORTS" read-only="true" /> <!-- 其他采用默认事务方式 --> <tx:method name="*" /> </tx:attributes> </tx:advice> <!-- Spring aop事务管理 --> <aop:config> <!-- 配置切入点 --> <aop:pointcut id="transactionPointcut" expression="execution(* com.cherry.mall..*.service..*.*(..))" /> <!-- 指定在txAdvice切入点应用txAdvice事务增强处理 --> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans> ``` 报错信息: ``` org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134) at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:1014) at com.cherry.mall.common.dao.CommonDAO.getHBSession(CommonDAO.java:29) at com.cherry.mall.common.dao.CommonDAO.create(CommonDAO.java:48) at com.cherry.mall.common.service.CommonServiceImpl.create(CommonServiceImpl.java:72) at com.cherry.mall.message.service.impl.MessageServiceImpl.create(MessageServiceImpl.java:30) at com.cherry.mall.message.service.impl.MessageServiceImpl.create(MessageServiceImpl.java:1) at com.cherry.mall.message.controller.MessageController.save(MessageController.java:42) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) ``` 报错地点: ![图片说明](https://img-ask.csdn.net/upload/201708/17/1502946641_931733.png) 求大神指教

spring mvc+hibernate4事务控制

``` web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>spring-mvc</display-name> <!--配置欢迎界面 --> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/exception.jsp</location> </error-page> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Log4j配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/log4j.properties</param-value> </context-param> <!-- 开一条watchdog线程每60秒扫描一下配置文件的变化 --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!--配置log4j包 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!--配置listener --> <!--在这里可以配置spring的监听器,启动的时候需要把spring中的bean都注册到spring容器中 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value><!-- 强制转码 --> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--配置servlet --> <!--我们希望spring的控制器比其他servlet优先启动,所以你需要设置load-on-startup 这个东西:值越小越先启动(0-5),没有或者为负数的时候,servlet被选用的时候才加载--> <servlet> <servlet-name>controller</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:controll-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>controller</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <filter> <filter-name>openSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> <init-param> <param-name>singleSession</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>sessionFactory</param-name> <param-value>sessionFactory</param-value> </init-param> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> 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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr" 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.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:hibernate.properties</value> </list> </property> </bean> <!-- DWR配置--> <dwr:annotation-config></dwr:annotation-config> <!-- 扫描需要转换的java对象 --> <dwr:annotation-scan scanRemoteProxy="true" base-package="com.tb.service" /> <!-- 部署项目时, 请把debug设为false <dwr:controller id="dwrController" debug="true" /> --> <!--DWR初始化配置 --> <dwr:configuration></dwr:configuration> <!-- 配置数据源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${db.driver}</value> </property> <property name="jdbcUrl"> <value>${db.url}</value> </property> <property name="user"> <value>${db.user}</value> </property> <property name="password"> <value>${db.password}</value> </property> <property name="maxPoolSize"> <value>300</value> </property> <property name="minPoolSize"> <value>1</value> </property> <property name="initialPoolSize"> <value>1</value> </property> <property name="maxIdleTime"> <value>60</value> </property> <property name="acquireIncrement"> <value>5</value> </property> <property name="acquireRetryAttempts"> <value>10</value> </property> <property name="acquireRetryDelay"> <value>1000</value> </property> <property name="autoCommitOnClose"> <value>true</value> </property> <property name="breakAfterAcquireFailure"> <value>false</value> </property> <property name="checkoutTimeout"> <value>100</value> </property> <property name="idleConnectionTestPeriod"> <value>60</value> </property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 让spring帮你扫描这个包底下的所有类,主要作用扫描跟数据库对应的实体类 --> <!-- 设置hibernate的属性 --> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.OracleDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_outer_join">true </prop> <prop key="hibernate.cglib.use_reflection_optimizer">true </prop> <prop key="hibernate.connection.useUnicode">true</prop> <prop key="hibernate.cache.use_query_cache">false</prop> <prop key="hibernate.default_batch_fetch_size">16</prop> <prop key="hibernate.c3p0.max_size">300</prop> <prop key="hibernate.c3p0.min_size">1</prop> <prop key="hibernate.c3p0.timeout">60</prop> <prop key="hibernate.c3p0.max_statements">100</prop> <prop key="hibernate.c3p0.idle_test_period">60</prop> <prop key="hibernate.c3p0.acquire_increment">5</prop> <prop key="hibernate.c3p0.validate">true</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> <property name="packagesToScan" value="com.tb.model"/> </bean> <!--事务配置 --> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 开启AOP监听 只对当前配置文件有效 --> <aop:aspectj-autoproxy expose-proxy="true" /> <!-- 开启注解事务 只对当前配置文件有效 --> <tx:annotation-driven transaction-manager="txManager"/> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="merge*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="put*" propagation="REQUIRED" /> <tx:method name="execute*" propagation="REQUIRED" rollback-for ="Exception.class" /> <tx:method name="tes*" propagation="REQUIRED" /> <tx:method name="use*" propagation="REQUIRED" /> <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到 --> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="count*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" rollback-for ="Exception.class"/> </tx:attributes> </tx:advice> <bean id="transactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true" lazy-init="true"> <property name="transactionManager" ref="txManager"></property> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="save*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="tes*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="execute*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="query*">PROPAGATION_REQUIRED, readOnly,-Exception</prop> <prop key="load*">PROPAGATION_REQUIRED, -Exception</prop> </props> </property> </bean> <!-- 只对业务逻辑层实施事务 --> <aop:config expose-proxy="true"> <aop:pointcut id="txPointcut" expression="execution(* com.tb.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut" /> </aop:config> <!-- --> <!--配置拦截器 在springmvc的控制器配置文件中,你就可以这么配置拦截器,具体你在拦截器里面做什么,自己去做 <mvc:interceptors> 多个拦截器,顺序执行 <mvc:interceptor> 这里的path符号有/*, /**, *, ? 等,对于student.do?param=1从?开始不作为path 如果不配置或/*,将拦截所有的Controller <mvc:mapping path="/student/save*" /> <bean class="spring.common.interceptor.FromDupInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> --> </beans> controll-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" xmlns:p="http://www.springframework.org/schema/p" 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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.tb"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <context:component-scan base-package="com.tb"/> <!-- json --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonHttpMessageConverter"/> </list> </property> </bean> <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" valu-e=".jsp"/> </bean> </beans> 以上为配置文件:包路径分别为com.tb.action;com.tb.service;com.tb.model;com.tb.dao; 其中com.tb.service下面又分com.tb.service.impl;com.tb.dao包下又分com.tb.dao.impl; 但是现在测试事物一直控制不了,请大神帮忙原因。测试方法: Controller.java @RequestMapping(params = "executeSearch") @Transactional public String executeSearch(HttpServletRequest request) { //测试事物控制。 infoService.test(); return "info/search"; } ServiceImpl.java public void test(){ try { infoDAO.test(); } catch (Exception e) { e.printStackTrace(); } } Service.java @Transactional public void test(); DaoImpl.java @Transactional public void test() { try { String sql = "update operation_log set username='1' where id='1'"; List<Object> condition = new ArrayList<Object>(); this.executeUpdateBySql(sql, condition); String sql1 = "update operation_log set username=33, where id='1'"; this.executeUpdateBySql(sql1, condition); } catch (RuntimeException e) { e.printStackTrace(); } } DaoImpl.java继承HibernateDao HibernateDao.java /***************注入***********/ @Resource private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public Session getSession() { //事务配置后,可通过getCurrentSession方法获得session return sessionFactory.getCurrentSession(); } public int executeUpdateBySql(final String sql,final List<Object> conditions){ try { Query query = getSession().createSQLQuery(sql); if(conditions!=null && conditions.size()>0){ for(int i=0;i<conditions.size();i++){ if(conditions.get(i)!=null && !conditions.get(i).equals("")){ query.setParameter(i, conditions.get(i)); } } } return query.executeUpdate(); } catch (RuntimeException e) { throw e; }finally{ System.out.println(getSessionFactory().getCurrentSession().beginTransaction().isActive()); } } 整体代码是这样的,在运行daoImpl.java中test()方法的时候执行第一条SQL时会提交事物,直接修改数据库中的值,执行第二条SQL时会报错,理论上应该都不提交事物。但实际上第一条执行了之后就提交事物了,不知道是我框架问题还是我写的问题,求大神帮忙指出问题所在。万分感谢! ```

org.apache.ibatis.exceptions.PersistenceException怎么解决?

调试一个开源项目出现报错,项目所有sql都会报空指针异常 ``` 严重: Servlet.service() for servlet [springMvc] in context with path [/mallapp] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: java.lang.NullPointerException ### The error may exist in file [H:\WorksSpace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\wtpwebapps\mallapp\WEB-INF\classes\mybatis\category\CategoryMapper.xml] ### The error may involve CategoryMapper.listAll-Inline ### The error occurred while setting parameters ### SQL: select category_name, category_img, sort, category_id, super_id from shop_category where super_id =? order by sort ### Cause: java.lang.NullPointerException] with root cause java.lang.NullPointerException at org.apache.ibatis.type.BaseTypeHandler.setParameter(BaseTypeHandler.java:43) at org.apache.ibatis.scripting.defaults.DefaultParameterHandler.setParameters(DefaultParameterHandler.java:81) at org.apache.ibatis.executor.statement.PreparedStatementHandler.parameterize(PreparedStatementHandler.java:80) at org.apache.ibatis.executor.statement.RoutingStatementHandler.parameterize(RoutingStatementHandler.java:61) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:62) at com.sun.proxy.$Proxy84.parameterize(Unknown Source) at org.apache.ibatis.executor.ReuseExecutor.prepareStatement(ReuseExecutor.java:79) at org.apache.ibatis.executor.ReuseExecutor.doQuery(ReuseExecutor.java:56) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:267) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:137) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:96) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:77) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:108) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:102) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:358) at com.sun.proxy.$Proxy74.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:198) at com.yq.dao.DaoSupport.findForList(DaoSupport.java:118) at com.yq.service.category.impl.CategoryService.listAll(CategoryService.java:62) at com.yq.service.category.impl.CategoryService$$FastClassBySpringCGLIB$$51d95cd7.invoke(<generated>) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644) at com.yq.service.category.impl.CategoryService$$EnhancerBySpringCGLIB$$c2253a36.listAll(<generated>) at com.yq.controller.category.CategoryController.list(CategoryController.java:80) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at com.alibaba.druid.support.http.WebStatFilter.doFilter(WebStatFilter.java:123) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) ``` CategoryMapper.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="CategoryMapper"> <!--表名 --> <sql id="tableName"> shop_category </sql> <!-- 字段 --> <sql id="Field"> category_name, category_img, sort, category_id, super_id </sql> <!-- 字段值 --> <sql id="FieldValue"> #{category_name}, #{category_img}, #{sort}, #{category_id}, #{super_id} </sql> <!-- 新增--> <insert id="save" parameterType="pd"> insert into <include refid="tableName"></include> ( <include refid="Field"></include> ) values ( <include refid="FieldValue"></include> ) </insert> <!-- 删除--> <delete id="delete" parameterType="pd"> delete from <include refid="tableName"></include> where category_id = #{category_id} </delete> <!-- 修改 --> <update id="edit" parameterType="pd"> update <include refid="tableName"></include> set category_name = #{category_name}, category_img = #{category_img}, sort = #{sort} where category_id = #{category_id} </update> <!-- 通过ID获取数据 --> <select id="findById" parameterType="pd" resultType="pd"> select <include refid="Field"></include> from <include refid="tableName"></include> where category_id = #{category_id} </select> <!-- 列表 --> <select id="datalistPage" parameterType="page" resultType="pd"> select <include refid="Field"></include> from <include refid="tableName"></include> where 1=1 and super_id =#{pd.super_id} order by sort </select> <!-- 列表(全部) --> <select id="listAll" parameterType="pd" resultType="pd"> select <include refid="Field"></include> from <include refid="tableName"></include> where super_id =#{super_id} order by sort </select> <!-- 批量删除 --> <delete id="deleteAll" parameterType="String"> delete from <include refid="tableName"></include> where category_id in <foreach item="item" index="index" collection="array" open="(" separator="," close=")"> #{item} </foreach> </delete> </mapper> ``` mybatis-config.xml ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="true" /><!-- 全局映射器启用缓存 --> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> <!-- 打印查询语句 --> <setting name="logImpl" value="LOG4J" /> </settings> <typeAliases> <typeAlias type="org.change.entity.system.User" alias="User"/> <typeAlias type="org.change.entity.system.Role" alias="Role"/> <typeAlias type="org.change.entity.system.Menu" alias="Menu"/> <typeAlias type="org.change.entity.system.Dictionaries" alias="Dictionaries"/> <typeAlias type="org.change.entity.system.Department" alias="Department"/> <typeAlias type="org.change.util.PageData" alias="pd"/> <!-- 分页 --> <typeAlias type="org.change.entity.Page" alias="Page"/> </typeAliases> <plugins> <plugin interceptor="org.change.plugin.PagePlugin"> <property name="dialect" value="mysql"/> <property name="pageSqlId" value=".*listPage.*"/> </plugin> </plugins> </configuration> ``` DAO.java ``` public interface DAO { /** * 保存对象 * @param str * @param obj * @return * @throws Exception */ public Object save(String str, Object obj) throws Exception; /** * 修改对象 * @param str * @param obj * @return * @throws Exception */ public Object update(String str, Object obj) throws Exception; /** * 删除对象 * @param str * @param obj * @return * @throws Exception */ public Object delete(String str, Object obj) throws Exception; /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForObject(String str, Object obj) throws Exception; /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForList(String str, Object obj) throws Exception; /** * 查找对象封装成Map * @param s * @param obj * @return * @throws Exception */ public Object findForMap(String sql, Object obj, String key , String value) throws Exception; } ``` DaoSupport.java ``` @Repository("daoSupport") public class DaoSupport implements DAO { @Resource(name = "sqlSessionTemplate") private SqlSessionTemplate sqlSessionTemplate; /** * 保存对象 * @param str * @param obj * @return * @throws Exception */ public Object save(String str, Object obj) throws Exception { return sqlSessionTemplate.insert(str, obj); } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public Object batchSave(String str, List objs )throws Exception{ return sqlSessionTemplate.insert(str, objs); } /** * 修改对象 * @param str * @param obj * @return * @throws Exception */ public Object update(String str, Object obj) throws Exception { return sqlSessionTemplate.update(str, obj); } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public void batchUpdate(String str, List objs )throws Exception{ SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory(); //批量执行器 SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false); try{ if(objs!=null){ for(int i=0,size=objs.size();i<size;i++){ sqlSession.update(str, objs.get(i)); } sqlSession.flushStatements(); sqlSession.commit(); sqlSession.clearCache(); } }finally{ sqlSession.close(); } } /** * 批量更新 * @param str * @param obj * @return * @throws Exception */ public Object batchDelete(String str, List objs )throws Exception{ return sqlSessionTemplate.delete(str, objs); } /** * 删除对象 * @param str * @param obj * @return * @throws Exception */ public Object delete(String str, Object obj) throws Exception { return sqlSessionTemplate.delete(str, obj); } /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForObject(String str, Object obj) throws Exception { return sqlSessionTemplate.selectOne(str, obj); } /** * 查找对象 * @param str * @param obj * @return * @throws Exception */ public Object findForList(String str, Object obj) throws Exception { return sqlSessionTemplate.selectList(str, obj); } public Object findForMap(String str, Object obj, String key, String value) throws Exception { return sqlSessionTemplate.selectMap(str, obj, key); } } ``` spring.xml ``` <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd "> <!-- 配置事务管理器 --> <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <!-- 阿里 druid数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <!-- 数据库基本信息配置 --> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <property name="filters" value="${filters}" /> <!-- 最大并发连接数 --> <property name="maxActive" value="${maxActive}" /> <!-- 初始化连接数量 --> <property name="initialSize" value="${initialSize}" /> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="${maxWait}" /> <!-- 最小空闲连接数 --> <property name="minIdle" value="${minIdle}" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testWhileIdle" value="${testWhileIdle}" /> <property name="testOnBorrow" value="${testOnBorrow}" /> <property name="testOnReturn" value="${testOnReturn}" /> <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="${removeAbandoned}" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="${logAbandoned}" /> </bean> <!-- 启用注解 --> <context:annotation-config /> <!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 --> <context:component-scan base-package="com"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 注解方式配置事务--> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事务 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" /> <tx:method name="*" propagation="SUPPORTS"/> </tx:attributes> </tx:advice> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- 事物处理 --> <aop:config> <aop:pointcut id="pc" expression="execution(* com.*.service..*(..))" /> <aop:advisor pointcut-ref="pc" advice-ref="txAdvice" /> </aop:config> <!-- 配置mybatis --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <!-- mapper扫描 --> <property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg ref="sqlSessionFactory" /> </bean> </beans> ```

Spring + Hibernate4 无法将数据写入数据【请教】

<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p class="MsoNormal" style="text-align: center;" align="center"> </p> <p class="MsoNormal"><span lang="EN-US"> 问题:</span></p> <p class="MsoNormal"><span lang="EN-US">通过Junit单元测试Service可以将数据写入数据库;但部署却无法向数据库写入数据。</span></p> <h1> <strong><span lang="EN-US">1、</span></strong><span lang="EN-US"><strong>环境</strong>:</span> </h1> <p class="MsoListParagraph" style="margin-left: 18.0pt; text-indent: 0cm;"><span lang="EN-US">Spring 3.1.2</span></p> <p class="MsoListParagraph" style="margin-left: 18.0pt; text-indent: 0cm;"><span lang="EN-US">Hibernate 4.1.4</span></p> <p class="MsoListParagraph" style="margin-left: 18.0pt; text-indent: 0cm;"><span lang="EN-US">Jdk1.6</span></p> <h1>2、配置:</h1> <p class="MsoListParagraph">&lt;!--[if !supportLists]--&gt;<strong><span lang="EN-US">1<span lang="EN-US">     </span></span></strong>&lt;!--[endif]--&gt;<strong><span lang="EN-US"> </span></strong></p> <p class="MsoListParagraph">&lt;!--[if !supportLists]--&gt;<strong><span lang="EN-US">2<span lang="EN-US">     </span></span></strong>&lt;!--[endif]--&gt;<strong><span lang="EN-US"> </span></strong></p> <h2> <span lang="EN-US">2.1、</span><span lang="EN-US">Web.xml</span> </h2> <p class="MsoNormal" align="left"><span lang="EN-US">&lt;?</span><span lang="EN-US">xml</span><span lang="EN-US"> <span lang="EN-US">version</span>=<em><span lang="EN-US">"1.0"</span></em> <span lang="EN-US">encoding</span>=<em><span lang="EN-US">"UTF-8"</span></em><span lang="EN-US">?&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US"> </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">&lt;</span><span lang="EN-US">web-app</span><span lang="EN-US"> <span lang="EN-US">xmlns:xsi</span>=<em><span lang="EN-US">"http://www.w3.org/2001/XMLSchema-instance"</span></em> <span lang="EN-US">xmlns</span>=<em><span lang="EN-US">"http://java.sun.com/xml/ns/javaee"</span></em> <span lang="EN-US">xmlns:web</span>=<em><span lang="EN-US">"http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"</span></em> <span lang="EN-US">xsi:schemaLocation</span>=<em><span lang="EN-US">"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"</span></em> <span lang="EN-US">id</span>=<em><span lang="EN-US">"WebApp_ID"</span></em> <span lang="EN-US">version</span>=<em><span lang="EN-US">"2.5"</span></em><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span><span lang="EN-US">&lt;</span><span lang="EN-US">display-name</span><span lang="EN-US">&gt;</span><span style="text-decoration: underline;"><span lang="EN-US">springmvc</span></span><span lang="EN-US">&lt;/</span><span lang="EN-US">display-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span><span lang="EN-US">&lt;</span><span lang="EN-US">welcome-file-list</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">welcome-file</span><span lang="EN-US">&gt;</span><span lang="EN-US">index.html</span><span lang="EN-US">&lt;/</span><span lang="EN-US">welcome-file</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">welcome-file</span><span lang="EN-US">&gt;</span><span lang="EN-US">index.htm</span><span lang="EN-US">&lt;/</span><span lang="EN-US">welcome-file</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">welcome-file</span><span lang="EN-US">&gt;</span><span lang="EN-US">index.jsp</span><span lang="EN-US">&lt;/</span><span lang="EN-US">welcome-file</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span><span lang="EN-US">&lt;/</span><span lang="EN-US">welcome-file-list</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span><span lang="EN-US">&lt;!-- Spring ApplicationContext</span><span lang="EN-US">配置文件的路径</span><span lang="EN-US">,</span><span lang="EN-US">可使用通配符</span><span lang="EN-US">,</span><span lang="EN-US">多个路径用</span><span lang="EN-US">,</span><span lang="EN-US">号分隔</span><span lang="EN-US">此参数用于后面的</span><span lang="EN-US">Spring Context Loader --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span><span lang="EN-US">&lt;</span><span lang="EN-US">context-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">contextConfigLocation</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span><span style="text-decoration: underline;"><span lang="EN-US">classpath</span></span><span lang="EN-US">*:/applicationContext.xml</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span><span lang="EN-US">&lt;/</span><span lang="EN-US">context-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">listener</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">listener-class</span><span lang="EN-US">&gt;</span><span lang="EN-US">org.springframework.web.context.ContextLoaderListener</span><span lang="EN-US">&lt;/</span><span lang="EN-US">listener-class</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;/</span><span lang="EN-US">listener</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!--<span style="text-decoration: underline;">Dispathcer</span> <span style="text-decoration: underline;">Servlet</span> --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">servlet</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">servlet-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">spring-<span style="text-decoration: underline;">mvc</span></span><span lang="EN-US">&lt;/</span><span lang="EN-US">servlet-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">servlet-class</span><span lang="EN-US">&gt;</span><span lang="EN-US">org.springframework.web.servlet.DispatcherServlet</span><span lang="EN-US">&lt;/</span><span lang="EN-US">servlet-class</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">init-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">            </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">contextConfigLocation</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">            </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span><span lang="EN-US">/WEB-INF/spring-mvc.xml</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;/</span><span lang="EN-US">init-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">load-on-startup</span><span lang="EN-US">&gt;</span><span lang="EN-US">1</span><span lang="EN-US">&lt;/</span><span lang="EN-US">load-on-startup</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;/</span><span lang="EN-US">servlet</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- Spring MVC <span style="text-decoration: underline;">Servlet</span> </span><span lang="EN-US">拦截</span><span lang="EN-US">.do</span><span lang="EN-US">结尾的请求</span><span lang="EN-US">--&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">servlet-mapping</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">servlet-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">spring-<span style="text-decoration: underline;">mvc</span></span><span lang="EN-US">&lt;/</span><span lang="EN-US">servlet-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">url-pattern</span><span lang="EN-US">&gt;</span><span lang="EN-US">*.do</span><span lang="EN-US">&lt;/</span><span lang="EN-US">url-pattern</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;/</span><span lang="EN-US">servlet-mapping</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- Filter </span><span lang="EN-US">定义</span><span lang="EN-US"> --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">encodingFilter</span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter-class</span><span lang="EN-US">&gt;</span><span lang="EN-US">org.springframework.web.filter.CharacterEncodingFilter</span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter-class</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">init-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">            </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">encoding</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">            </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span><span lang="EN-US">UTF-8</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;/</span><span lang="EN-US">init-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">init-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">            </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">forceEncoding</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">            </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span><span lang="EN-US">true</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;/</span><span lang="EN-US">init-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter-mapping</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">encodingFilter</span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span><span lang="EN-US">&lt;</span><span lang="EN-US">url-pattern</span><span lang="EN-US">&gt;</span><span lang="EN-US">/*</span><span lang="EN-US">&lt;/</span><span lang="EN-US">url-pattern</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter-mapping</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">   </span><span lang="EN-US">&lt;!--openSessionInView--&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">   </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">openSessionInView</span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter-class</span><span lang="EN-US">&gt;</span><span lang="EN-US">org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter-class</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">&lt;</span><span lang="EN-US">init-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">           </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">sessionFactoryBeanName</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">           </span><span lang="EN-US">&lt;</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span><span lang="EN-US">sessionFactory</span><span lang="EN-US">&lt;/</span><span lang="EN-US">param-value</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">&lt;/</span><span lang="EN-US">init-param</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US"> </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter-mapping</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">&lt;</span><span lang="EN-US">filter-name</span><span lang="EN-US">&gt;</span><span lang="EN-US">openSessionInView</span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter-name</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">&lt;</span><span lang="EN-US">url-pattern</span><span lang="EN-US">&gt;</span><span lang="EN-US">/*</span><span lang="EN-US">&lt;/</span><span lang="EN-US">url-pattern</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;/</span><span lang="EN-US">filter-mapping</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US"> </span></p> <p class="MsoListParagraph" style="margin-left: 18.0pt; text-indent: 0cm;"><span lang="EN-US">&lt;/</span><span lang="EN-US">web-app</span><span lang="EN-US">&gt;</span></p> <h2> <span lang="EN-US">2.2<span lang="EN-US">     </span></span><span lang="EN-US">applicationContext.xml</span> </h2> <p class="MsoNormal"><span lang="EN-US">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">&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:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">          &lt;!--</span><span lang="EN-US">扫描并自动装配</span><span lang="EN-US"> --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;context:annotation-config /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;context:component-scan base-package="com.sp" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">   &lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;property name="locations"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                            &lt;value&gt;classpath:application.properties&lt;/value&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;/property&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;/bean&gt;</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">   &lt;!-- </span><span lang="EN-US">数据源配置</span><span lang="EN-US"> --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">    &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;!-- Connection Info --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="driverClassName" value="${jdbc.driver}" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="url" value="${jdbc.url}" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="username" value="${jdbc.username}" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="password" value="${jdbc.password}" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;!-- Connection Pooling Info --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="maxActive" value="${dbcp.maxActive}" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="maxIdle" value="${dbcp.maxIdle}" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="defaultAutoCommit" value="false" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        </span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;!-- </span><span lang="EN-US">连接</span><span lang="EN-US">Idle</span><span lang="EN-US">一个小时后超时</span><span lang="EN-US"> --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="timeBetweenEvictionRunsMillis" value="3600000" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">        &lt;property name="minEvictableIdleTimeMillis" value="3600000" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">    &lt;/bean&gt;</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt;              </span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;property name="hibernateProperties"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                            &lt;props&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                                     &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                                     &lt;prop key="hibernate.hbm2ddl.auto"&gt;update&lt;/prop&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                                     &lt;prop key="hibernate.connection.autocommit"&gt;true&lt;/prop&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                                     &lt;prop key="hibernate.current_session_context_class"&gt;org.springframework.orm.hibernate4.SpringSessionContext&lt;/prop&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                                     &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                                     &lt;prop key="hibernate.format_sql"&gt;true&lt;/prop&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                            &lt;/props&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;/property&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   </span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;property name="packagesToScan"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                            &lt;list&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                                     &lt;value&gt;com.sp.dao&lt;/value&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                                     &lt;value&gt;com.sp.entity.dict&lt;/value&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                            &lt;/list&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;/property&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;/bean&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" abstract="false" lazy-init="default" autowire="default"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;property name="sessionFactory"&gt;&lt;ref bean="sessionFactory" /&gt;&lt;/property&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;/bean&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;!-- </span><span lang="EN-US">事务管理配置</span><span lang="EN-US"> --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;!--&lt;tx:annotation-driven transaction-manager="transactionManager"&gt;&lt;/tx:annotation-driven&gt;--&gt; </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;tx:advice id="txAdvice" transaction-manager="transactionManager"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;tx:attributes&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                            &lt;tx:method name="insert*" read-only="false" propagation="REQUIRED" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                            &lt;tx:method name="get*" read-only="false" propagation="REQUIRED" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">            &lt;tx:method name="add*" read-only="false" propagation="REQUIRED" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">            &lt;tx:method name="update*" read-only="false" propagation="REQUIRED" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">            &lt;tx:method name="delete*" read-only="false" propagation="REQUIRED" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;/tx:attributes&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;/tx:advice&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;aop:config&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;aop:advisor pointcut="execution(* com.sp.service.*.*(..))"  advice-ref="txAdvice"/&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;/aop:config&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">&lt;/beans&gt;</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <h2> <span lang="EN-US">2.3<span lang="EN-US"> </span></span><span lang="EN-US">spring-mvc.xml</span> </h2> <p class="MsoNormal"><span lang="EN-US">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">&lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"</span></p> <p class="MsoNormal"><span lang="EN-US">         xmlns:context="http://www.springframework.org/schema/context"</span></p> <p class="MsoNormal"><span lang="EN-US">         xmlns:mvc="http://www.springframework.org/schema/mvc"</span></p> <p class="MsoNormal"><span lang="EN-US">         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd</span></p> <p class="MsoNormal"><span lang="EN-US">                   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd</span></p> <p class="MsoNormal"><span lang="EN-US">        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;!-- </span><span lang="EN-US">启动注解驱动的</span><span lang="EN-US">SpringMVC</span><span lang="EN-US">功能,注册请求</span><span lang="EN-US">URL</span><span lang="EN-US">和注解</span><span lang="EN-US">POJO</span><span lang="EN-US">类方法的映射</span><span lang="EN-US"> --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;mvc:annotation-driven /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;!-- </span><span lang="EN-US">自动扫描且只扫描</span><span lang="EN-US">@Controller --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;context:component-scan base-package="com.sp.web" use-default-filters="false"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;/context:component-scan&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;context:component-scan base-package="com.sp.dao.impl"&gt;&lt;/context:component-scan&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;context:component-scan base-package="com.sp.service.impl"&gt;&lt;/context:component-scan&gt;</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;mvc:default-servlet-handler /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;!-- </span><span lang="EN-US">对模型视图名称的解析,在请求时模型视图名称添加后缀。定义</span><span lang="EN-US">JSP --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;property name="prefix" value="/WEB-INF/views/" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">                   &lt;property name="suffix" value=".jsp" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;/bean&gt;</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;!-- </span><span lang="EN-US">支持上传文件</span><span lang="EN-US"> --&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">         &lt;bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">&lt;/beans&gt;</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <h2> <span lang="EN-US">2.4<span lang="EN-US">  </span></span><span lang="EN-US">hibernate.cfg.xml</span> </h2> <p class="MsoNormal" align="left"><span lang="EN-US">&lt;?</span><span lang="EN-US">xml</span><span lang="EN-US"> <span lang="EN-US">version</span>=<em><span lang="EN-US">'1.0'</span></em> <span lang="EN-US">encoding</span>=<em><span lang="EN-US">'utf-8'</span></em><span lang="EN-US">?&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">&lt;!</span><span lang="EN-US">DOCTYPE</span><span lang="EN-US"> <span lang="EN-US">hibernate-configuration</span> <span lang="EN-US">PUBLIC</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     <span lang="EN-US">"-//Hibernate/Hibernate Configuration DTD 3.0//EN"</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     <span lang="EN-US">"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">        </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">&lt;</span><span lang="EN-US">hibernate-configuration</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">  </span><span lang="EN-US">&lt;</span><span lang="EN-US">session-factory</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- Database connection settings--&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"connection.driver_class"</span></em><span lang="EN-US">&gt;</span>com.mysql.jdbc.Driver<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"connection.url"</span></em><span lang="EN-US">&gt;</span>jdbc:mysql://<span style="text-decoration: underline;">localhost</span>:3306/test<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"connection.username"</span></em><span lang="EN-US">&gt;</span>root<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"connection.password"</span></em><span lang="EN-US">&gt;</span>password<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- JDBC connection pool (use the built-in) --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"connection.pool_size"</span></em><span lang="EN-US">&gt;</span>1<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- SQL dialect </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    &lt;property name="dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/property&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- Enable Hibernate's automatic session context management --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- &lt;property name="current_session_context_class"&gt;thread&lt;/property&gt; --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US"> </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- Disable the second-level cache  --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- &lt;property name="cache.provider_class"&gt;org.hibernate.cache.internal.NoCacheProvider&lt;/property&gt;--&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- Echo all executed SQL to <span style="text-decoration: underline;">stdout</span> --&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"show_sql"</span></em><span lang="EN-US">&gt;</span>true<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"format_sql"</span></em><span lang="EN-US">&gt;</span>true<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;!-- Drop and re-create the database schema on startup--&gt;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"hbm2ddl.auto"</span></em><span lang="EN-US">&gt;</span>update<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">&lt;</span><span lang="EN-US">property</span><span lang="EN-US"> <span lang="EN-US">name</span>=<em><span lang="EN-US">"javax.persistence.validation.mode"</span></em><span lang="EN-US">&gt;</span>none<span lang="EN-US">&lt;/</span><span lang="EN-US">property</span><span lang="EN-US">&gt;</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">     </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">  </span><span lang="EN-US">&lt;/</span><span lang="EN-US">session-factory</span><span lang="EN-US">&gt;</span></p> <p class="MsoNormal"><span lang="EN-US">&lt;/</span><span lang="EN-US">hibernate-configuration</span><span lang="EN-US">&gt;</span></p> <p class="MsoListParagraph" style="margin-left: 18.0pt; text-indent: 0cm;"><strong><span lang="EN-US"> </span></strong></p> <h1> <span lang="EN-US">3<span lang="EN-US">         </span></span><span lang="EN-US">代码:</span> </h1> <p class="MsoListParagraph">&lt;!--[if !supportLists]--&gt;<strong><span lang="EN-US">1<span lang="EN-US">     </span></span></strong>&lt;!--[endif]--&gt;<strong><span lang="EN-US"> </span></strong></p> <p class="MsoListParagraph">&lt;!--[if !supportLists]--&gt;<strong><span lang="EN-US">2<span lang="EN-US">     </span></span></strong>&lt;!--[endif]--&gt;<strong><span lang="EN-US"> </span></strong></p> <p class="MsoListParagraph">&lt;!--[if !supportLists]--&gt;<strong><span lang="EN-US">3<span lang="EN-US">     </span></span></strong>&lt;!--[endif]--&gt;<strong><span lang="EN-US"> </span></strong></p> <h2> <span lang="EN-US">3.1<span lang="EN-US">  </span></span><span lang="EN-US">Service</span><span lang="EN-US">层:</span> </h2> <p class="MsoNormal" align="left"><span lang="EN-US">@Component</span><span lang="EN-US">(</span><span lang="EN-US">"userService"</span><span lang="EN-US">)</span></p> <p class="MsoNormal" align="left"><strong><span lang="EN-US">public</span></strong><strong><span lang="EN-US">class</span></strong><span lang="EN-US"> UserServiceImpl </span><strong><span lang="EN-US">implements</span></strong><span lang="EN-US"> UserService{</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">@<span lang="EN-US">Autowired</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><strong><span lang="EN-US">private</span></strong><span lang="EN-US"> UserDao </span><span lang="EN-US">userDao</span><span lang="EN-US">;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US"> </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">@<span lang="EN-US">Autowired</span></span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><strong><span lang="EN-US">private</span></strong><span lang="EN-US"> FormValidator </span><span lang="EN-US">validator</span><span lang="EN-US">;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">@Override</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><strong><span lang="EN-US">public</span></strong><span lang="EN-US"> String userLogin(UserModel user) {</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       String password = </span><span lang="EN-US">userDao</span><span lang="EN-US">.userLogin(user);</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><strong><span lang="EN-US">if</span></strong><span lang="EN-US">(password.equals(user.getPassword())){</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">           </span><strong><span lang="EN-US">return</span></strong><span lang="EN-US">"sucess"</span><span lang="EN-US">;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       }</span><strong><span lang="EN-US">else</span></strong><span lang="EN-US">{</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">           </span><strong><span lang="EN-US">return</span></strong><span lang="EN-US">"false"</span><span lang="EN-US">;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       }</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    }</span></p> <p class="MsoNormal" align="left"><span lang="EN-US"> </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">@Override</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><strong><span lang="EN-US">public</span></strong><span lang="EN-US"> List&lt;ProjectType&gt; getAllProjectTypes(){</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       List&lt;ProjectType&gt; projectType = </span><span lang="EN-US">userDao</span><span lang="EN-US">.getAllProjectTypes();</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><strong><span lang="EN-US">return</span></strong><span lang="EN-US"> projectType;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    }</span></p> <p class="MsoNormal" align="left"><span lang="EN-US"> </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">//</span><span lang="EN-US">添加《项目类型》</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">@Override</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><strong><span lang="EN-US">public</span></strong><span lang="EN-US"> String addProjectType(</span><span lang="EN-US">@ModelAttribute</span><span lang="EN-US">(</span><span lang="EN-US">"newProjectType"</span><span lang="EN-US">)ProjectType projectType,BindingResult result,SessionStatus status){</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">validator</span><span lang="EN-US">.validate(projectType, result);</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><strong><span lang="EN-US">if</span></strong><span lang="EN-US">(result.hasErrors()){</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">           </span><strong><span lang="EN-US">return</span></strong><span lang="EN-US">"newProjectType"</span><span lang="EN-US">;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       }</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">userDao</span><span lang="EN-US">.save(projectType);</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">//status.setComplete();</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><strong><span lang="EN-US">return</span></strong><span lang="EN-US">"redirect:showProjectTypes.do"</span><span lang="EN-US">;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    }</span></p> <p class="MsoNormal" align="left"><span lang="EN-US"> </span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">//</span><span lang="EN-US">添加《项目类型》</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><span lang="EN-US">@Override</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    </span><strong><span lang="EN-US">public</span></strong><span lang="EN-US"> String addProjectType(ProjectType projectType) {</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><span lang="EN-US">userDao</span><span lang="EN-US">.save(projectType);</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">       </span><strong><span lang="EN-US">return</span></strong><span lang="EN-US">"redirect:showProjectTypes.do"</span><span lang="EN-US">;</span></p> <p class="MsoNormal" align="left"><span lang="EN-US">    }</span></p> <p class="MsoNormal"><span lang="EN-US">}</span></p> <h2> <span lang="EN-US">3.2<span lang="EN-US">   </span></span><span lang="EN-US">Control</span><span lang="EN-US">层</span> </h2> <p class="MsoNormal"><span lang="EN-US">@Controller</span></p> <p class="MsoNormal"><span lang="EN-US">@RequestMapping(value = "/user")</span></p> <p class="MsoNormal"><span lang="EN-US">public class UserController {</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">         @Autowired</span></p> <p class="MsoNormal"><span lang="EN-US">         private UserService userService;</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">    @Autowired</span></p> <p class="MsoNormal"><span lang="EN-US">    private FormValidator validator;</span></p> <p class="MsoNormal"><span lang="EN-US">    </span></p> <p class="MsoNormal"><span lang="EN-US">         @RequestMapping(value = "/login",method=RequestMethod.POST)</span></p> <p class="MsoNormal"><span lang="EN-US">         protected String handle(UserModel user,BindingResult result, Model model){</span></p> <p class="MsoNormal"><span lang="EN-US">                   String flag = userService.userLogin(user);</span></p> <p class="MsoNormal"><span lang="EN-US">                   System.out.println("flag:" + flag);</span></p> <p class="MsoNormal"><span lang="EN-US">                   if ("sucess".equals(flag)){</span></p> <p class="MsoNormal"><span lang="EN-US">                            return "sucess";</span></p> <p class="MsoNormal"><span lang="EN-US">                   }</span></p> <p class="MsoNormal"><span lang="EN-US">                   return "test1";</span></p> <p class="MsoNormal"><span lang="EN-US">         }</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">         @RequestMapping(value = "/showProjectTypes")</span></p> <p class="MsoNormal"><span lang="EN-US">         protected ModelAndView getAllProjectTypes(){</span></p> <p class="MsoNormal"><span lang="EN-US">                   ModelAndView mav = new ModelAndView("showProjectTypes");</span></p> <p class="MsoNormal"><span lang="EN-US">                   List&lt;ProjectType&gt; projectTypes = userService.getAllProjectTypes();</span></p> <p class="MsoNormal"><span lang="EN-US">                   mav.addObject("SEARCH_PROJECTTYPE_RESULTS_KEY", projectTypes);</span></p> <p class="MsoNormal"><span lang="EN-US">                   return mav;</span></p> <p class="MsoNormal"><span lang="EN-US">         }</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">         @RequestMapping(value = "/addProjectType",method=RequestMethod.GET)</span></p> <p class="MsoNormal"><span lang="EN-US">         protected ModelAndView newProjectTypeForm(){</span></p> <p class="MsoNormal"><span lang="EN-US">                   ModelAndView mav = new ModelAndView("newProjectType");</span></p> <p class="MsoNormal"><span lang="EN-US">                   ProjectType projectType = new ProjectType();</span></p> <p class="MsoNormal"><span lang="EN-US">                   mav.getModelMap().put("newProjectType", projectType);</span></p> <p class="MsoNormal"><span lang="EN-US">                   return mav;</span></p> <p class="MsoNormal"><span lang="EN-US">         }</span></p> <p class="MsoNormal"><span lang="EN-US">         </span></p> <p class="MsoNormal"><span lang="EN-US">         @RequestMapping(value = "/saveProjectType",method=RequestMethod.POST)</span></p> <p class="MsoNormal"><span lang="EN-US">         protected String addProjectType(@ModelAttribute("newProjectType")ProjectType projectType,BindingResult result,SessionStatus status){</span></p> <p class="MsoNormal"><span lang="EN-US">                   //return userService.addProjectType(projectType, result, status);</span></p> <p class="MsoNormal"><span lang="EN-US">                   return userService.addProjectType(projectType);</span></p> <p class="MsoNormal"><span lang="EN-US">         }</span></p> <p class="MsoNormal"><span lang="EN-US">}</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <h2> <span lang="EN-US">3.3<span lang="EN-US">    </span></span><span lang="EN-US">DAO</span><span lang="EN-US">@Component("userDao")</span> </h2> <p class="MsoNormal"><span lang="EN-US">public class UserDaoImpl implements UserDao{</span></p> <p class="MsoNormal"><span lang="EN-US">         @Autowired</span></p> <p class="MsoNormal"><span lang="EN-US">         private SessionFactory sessionFactory;</span></p> <p class="MsoNormal"><span lang="EN-US">    </span></p> <p class="MsoNormal"><span lang="EN-US">    public ProjectType getById(int id)</span></p> <p class="MsoNormal"><span lang="EN-US">    {</span></p> <p class="MsoNormal"><span lang="EN-US">        return (ProjectType) sessionFactory.getCurrentSession().get(ProjectType.class, id);</span></p> <p class="MsoNormal"><span lang="EN-US">    }</span></p> <p class="MsoNormal"><span lang="EN-US">    </span></p> <p class="MsoNormal"><span lang="EN-US">         @Override</span></p> <p class="MsoNormal"><span lang="EN-US">         public String userLogin(UserModel user) {</span></p> <p class="MsoNormal"><span lang="EN-US">                   return "123456";</span></p> <p class="MsoNormal"><span lang="EN-US">         }</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">         //</span><span lang="EN-US">获取数据</span></p> <p class="MsoNormal"><span lang="EN-US">         @Override</span></p> <p class="MsoNormal"><span lang="EN-US">         @SuppressWarnings("unchecked")</span></p> <p class="MsoNormal"><span lang="EN-US">         public List&lt;ProjectType&gt; getAllProjectTypes() {</span></p> <p class="MsoNormal"><span lang="EN-US">                   Criteria ceriteria = sessionFactory.getCurrentSession().createCriteria(ProjectType.class);</span></p> <p class="MsoNormal"><span lang="EN-US">                   return ceriteria.list();</span></p> <p class="MsoNormal"><span lang="EN-US">         }</span></p> <p class="MsoNormal"><span lang="EN-US"> </span></p> <p class="MsoNormal"><span lang="EN-US">         //</span><span lang="EN-US">新增数据;</span></p> <p class="MsoNormal"><span lang="EN-US">         @Override</span></p> <p class="MsoNormal"><span lang="EN-US">//      @Transactional(readOnly = true, propagation = Propagation.REQUIRED)</span></p> <p class="MsoNormal"><span lang="EN-US">         public int save(ProjectType projectType) {</span></p> <p class="MsoNormal"><span lang="EN-US">                   System.out.println("save:---");</span></p> <p class="MsoNormal"><span lang="EN-US">                   System.out.println(projectType.getIndex());</span></p> <p class="MsoNormal"><span lang="EN-US">                   System.out.println(projectType.getProjectType());</span></p> <p class="MsoNormal"><span lang="EN-US">                   System.out.println(projectType.getProjectTypeAbbr());</span></p> <p class="MsoNormal"><span lang="EN-US">                   </span></p> <p class="MsoNormal"><span lang="EN-US">                   return (Integer) sessionFactory.getCurrentSession().save(projectType);</span></p> <p class="MsoNormal"><span lang="EN-US">         }</span></p> <p> </p> <p class="MsoNormal"><span lang="EN-US">}</span></p> </div>

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

C++(数据结构与算法)78:---分而治之

一、分而治之的思想 分而治之方法与软件设计的模块化方法非常相似 分而治之通常不用于解决问题的小实例,而要解决一个问题的大实例。一般步骤为: ①把一个大实例分为两个或多个更小的实例 ②分别解决每个小实例 ③把这些小实例的解组合成原始大实例的解 二、实际应用之找出假币 问题描述 一个袋子有16个硬币,其中只有一个是假币,这个假币比其他的真币重量轻(其他所有真币的重量都是相同的)...

springboot+jwt实现token登陆权限认证

一 前言 此篇文章的内容也是学习不久,终于到周末有时间码一篇文章分享知识追寻者的粉丝们,学完本篇文章,读者将对token类的登陆认证流程有个全面的了解,可以动态搭建自己的登陆认证过程;对小项目而已是个轻量级的认证机制,符合开发需求;更多精彩原创内容关注公主号知识追寻者,读者的肯定,就是对作者的创作的最大支持; 二 jwt实现登陆认证流程 用户使用账号和面发出post请求 服务器接受到请求后使用私...

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

win10暴力查看wifi密码

刚才邻居打了个电话说:喂小灰,你家wifi的密码是多少,我怎么连不上了。 我。。。 我也忘了哎,就找到了一个好办法,分享给大家: 第一种情况:已经连接上的wifi,怎么知道密码? 打开:控制面板\网络和 Internet\网络连接 然后右击wifi连接的无线网卡,选择状态 然后像下图一样: 第二种情况:前提是我不知道啊,但是我以前知道密码。 此时可以利用dos命令了 1、利用netsh wlan...

女程序员,为什么比男程序员少???

昨天看到一档综艺节目,讨论了两个话题:(1)中国学生的数学成绩,平均下来看,会比国外好?为什么?(2)男生的数学成绩,平均下来看,会比女生好?为什么?同时,我又联想到了一个技术圈经常讨...

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

程序员写出这样的代码,能不挨骂吗?

当你换槽填坑时,面对一个新的环境。能够快速熟练,上手实现业务需求是关键。但是,哪些因素会影响你快速上手呢?是原有代码写的不够好?还是注释写的不够好?昨夜...

带了6个月的徒弟当了面试官,而身为高级工程师的我天天修Bug......

即将毕业的应届毕业生一枚,现在只拿到了两家offer,但最近听到一些消息,其中一个offer,我这个组据说客户很少,很有可能整组被裁掉。 想问大家: 如果我刚入职这个组就被裁了怎么办呢? 大家都是什么时候知道自己要被裁了的? 面试软技能指导: BQ/Project/Resume 试听内容: 除了刷题,还有哪些技能是拿到offer不可或缺的要素 如何提升面试软实力:简历, 行为面试,沟通能...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

!大部分程序员只会写3年代码

如果世界上都是这种不思进取的软件公司,那别说大部分程序员只会写 3 年代码,恐怕就没有程序员这种职业。

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

为什么你不想学习?只想玩?人是如何一步一步废掉的

不知道是不是只有我这样子,还是你们也有过类似的经历。 上学的时候总有很多光辉历史,学年名列前茅,或者单科目大佬,但是虽然慢慢地长大了,你开始懈怠了,开始废掉了。。。 什么?你说不知道具体的情况是怎么样的? 我来告诉你: 你常常潜意识里或者心理觉得,自己真正的生活或者奋斗还没有开始。总是幻想着自己还拥有大把时间,还有无限的可能,自己还能逆风翻盘,只不是自己还没开始罢了,自己以后肯定会变得特别厉害...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

早上躺尸,晚上干活:硅谷科技公司这么流行迟到?

硅谷科技公司上班时间OPEN早已不是什么新鲜事,早九晚五是常态,但有很多企业由于不打卡,员工们10点、11点才“姗姗来迟”的情况也屡见不鲜。 这种灵活的考勤制度为人羡慕,甚至近年来,国内某些互联网企业也纷纷效仿。不过,硅谷普遍弹性的上班制度是怎么由来的呢?这种“流行性迟到”真的有那么轻松、悠哉吗? 《动态规划专题班》 课程试听内容: 动态规划的解题要领 动态规划三大类 求最值/计数/可行性 常...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

Python爬虫,高清美图我全都要(彼岸桌面壁纸)

爬取彼岸桌面网站较为简单,用到了requests、lxml、Beautiful Soup4

无代码时代来临,程序员如何保住饭碗?

编程语言层出不穷,从最初的机器语言到如今2500种以上的高级语言,程序员们大呼“学到头秃”。程序员一边面临编程语言不断推陈出新,一边面临由于许多代码已存在,程序员编写新应用程序时存在重复“搬砖”的现象。 无代码/低代码编程应运而生。无代码/低代码是一种创建应用的方法,它可以让开发者使用最少的编码知识来快速开发应用程序。开发者通过图形界面中,可视化建模来组装和配置应用程序。这样一来,开发者直...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

Java岗开发3年,公司临时抽查算法,离职后这几题我记一辈子

前几天我们公司做了一件蠢事,非常非常愚蠢的事情。我原以为从学校出来之后,除了找工作有测试外,不会有任何与考试有关的事儿。 但是,天有不测风云,公司技术总监、人事总监两位大佬突然降临到我们事业线,叫上我老大,给我们组织了一场别开生面的“考试”。 那是一个风和日丽的下午,我翘着二郎腿,左手端着一杯卡布奇诺,右手抓着我的罗技鼠标,滚动着轮轴,穿梭在头条热点之间。 “淡黄的长裙~蓬松的头发...

大牛都会用的IDEA调试技巧!!!

导读 前天面试了一个985高校的实习生,问了他平时用什么开发工具,他想也没想的说IDEA,于是我抛砖引玉的问了一下IDEA的调试用过吧,你说说怎么设置断点...

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

立即提问
相关内容推荐