spring+ibatis事物配置问题为什么只有空指针才回滚,SQLException不回滚

transaction-manager="transactionManager">
tx:attributes




/tx:attributes
/tx:advice
aop:config
expression="execution(* *..services.impl.*Manager*.*(..))"
id="bankServicePc" />
pointcut-ref="bankServicePc" />
/aop:config

6个回答

其实这就像Java中有那么多的扩展异常类一样,每种种异常类用于表示某种异常,一旦你看到Null...Exception你就知道是空指定异常, 这种要体会体会

只有Runtime异常才回滚事务,非运行时异常不回滚事务。

当事务运行过程中发生异常时,事务可以被声明为回滚或继续提交。
默认情况下,当发生运行期异常时,事务将被回滚,发生检查型异常时,既不回滚也不提交,控制权交给外层调用。

这种默认的回滚规则在大多数情况下是适用的。不过用户也可以通过配置显式指定回滚规则:
通过指定带正号(+)或负号(-)的异常类名(或异常名片断)。当抛出负号型异常时,将触发事务回滚,当抛出正号型异常时,即使这个异常是检查型异常,事务也会提交。抛出异常或其父类异常名匹配规则中指定的异常类名,规则就生效.如:

PROPAGATION_REQUIRED,-Exception
只要业务方法运行时抛出的异常或其父类异常的类名包括"Exception",事务就回滚,以下异常都符合这条规则:SQLException、ParseException

因为spring默认的事务回滚规则为:运行期异常回滚,检查型异常不回滚,所以带负号的异常设置仅对检查型异常有意义.

一般开发中都会定义一个扩展自RuntimeException的异常类,如BizException或BusinessException异常类,用在需要进行异常回滚的地方,然后配置:
rollback-for="...BizException"

性能方面没什么问题

建议可以像我上面所说的,扩展一个异常类,用来捕捉需要回滚的地方
[code="java"]
/**

  • 自定义异常类. 需回滚的方法发生异常时将抛出该异常
  • @author qiuzj
    *
    */
    @SuppressWarnings("serial")
    public class RollbackException extends RuntimeException {

    public RollbackException() {
    super();
    }

    public RollbackException(String message, Throwable cause) {
    super(message, cause);
    }

    public RollbackException(String message) {
    super(message);
    }

    public RollbackException(Throwable cause) {
    super(cause);
    }

}
[/code]

问题补充:
[color=red]zhanjia ,我想假如要扩展RuntimeException类,但是捕捉异常,还是在
(SQLException e) {
throw new RollbackException();
}
呀。


是啊,也是这样用,在业务层这样用,即在添加了事务的那一层这样抛出

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
spring+ibatis事物配置问题为什么只有空指针才回滚,SQLException不回滚
<tx:advice id="transactionManagerAdivice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" read-only="false" rollback-for="Exception"/> <tx:method name="update*" read-only="false" rollback-for="Throwable"/> <tx:method name="save*" read-only="false" rollback-for="Throwable"/> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* *..services.impl.*Manager*.*(..))" id="bankServicePc" /> <aop:advisor advice-ref="transactionManagerAdivice" pointcut-ref="bankServicePc" /> </aop:config>
Spring ibatis事务配置不成功
各位兄弟姐妹帮我看看吧,这个配置事务怎么也不行。 访问地址是:http://localhost:8080/gen/logon.do?method=1 工程直接可以导进eclipse里 spring MVC + ibatis
spring整合iBATIS配置问题
[b]各位专家,我在用myeclipse学习spring整合iBATIS的时候,当我在文件applicationContext.xml里设置,configLocationl的属性用于指向sqlMapConfig.xml文件时,如下: <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation"> <value>/WEB-INF/sqlMapConfig.xml</value> </property> <property name="dataSource"><ref local="dataSource"/></property> </bean> 无论如何书写 <value>Web-inf/sqlMapConfig.xml</value>, 控制台报错: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlMapClient' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/sqlMapConfig.xml] sqlMapConfig.xml文件如下 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <sqlMap url="file:///e:/workspace/jsf+richfaces/src/com/sqlMap.xml"/> </sqlMapConfig> 我把文件sqlMapConfig.xml和applicationContext.xml都放在WEB-INF目录下,到底问题出在哪呀,请各位专家指点
spring boot mybatis 枚举错误,无法映射
spring boot mybatis 枚举错误 * 今天遇到一个问题,解决了好几个小时,没有搞定,搞到现在,有大佬可以帮我看下吗?万分感谢,没有分了,枚举映射,在idea中可以使用, 部署使用java -jar 方式就报错 * jdk1.8 * mybatis3.0.7.1 * application.yml环境为prod * ``` mybatis-plus: #枚举 typeHandlersPackage: com.xxx.common.module.handler ``` 1. Enum代码 ``` /** * Enum - 状态 * * @author xxx * @version 1.0.0 */ @JSONType(serializeEnumAsJavaBean = true) @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum StatusEnum implements BaseEnum<StatusEnum, Integer> { /** 删除 */ 删除(-1, "删除"), /** 无效 */ 无效(0, "无效"), /** 有效 */ 有效(1, "有效"); /** * 值. */ private Integer value; /** * 名称. */ private String name ; static { subClass.add(StatusEnum.class); } StatusEnum(Integer value, String name) { this.value = value; this.name = name; } @Override public Integer getValue() { return value; } public void setValue(Integer value) { this.value = value; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } //根据key获取枚举 public static StatusEnum getEnumByValue(Integer value){ if (null == value){ return null; } for(StatusEnum e: StatusEnum.values()){ if(e.getValue().equals(value)){ return e; } } return null; } } ``` 2. 枚举转换处理器 ``` package com.xxx.common.module.handler; import com.xxx.common.module.enums.*; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedTypes; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * 枚举转换处理器 * * @author xxx * @version 1.0.0 */ @Slf4j @MappedTypes(value = {StatusEnum.class}) public final class BaseEnumTypeHandler<E extends BaseEnum> extends BaseTypeHandler<E> { private Class<E> type; private E[] enums; public BaseEnumTypeHandler() { } public BaseEnumTypeHandler(Class<E> type) { if (type == null) { throw new IllegalArgumentException("Type argument cannot be null"); } this.type = type; this.enums = this.type.getEnumConstants(); if (this.enums == null) { throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type."); } } @Override public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException { //BaseTypeHandler 进行非空校验 log.debug("index : {}, parameter : {},jdbcType : {} ", i, parameter.getValue(), jdbcType); if (jdbcType == null) { ps.setObject(i, parameter.getValue()); } else { ps.setObject(i, parameter.getValue(), jdbcType.TYPE_CODE); } } @Override public E getNullableResult(ResultSet rs, String columnName) throws SQLException { Object code = rs.getObject(columnName); if (rs.wasNull()) { return null; } return getEnmByCode(code); } @Override public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException { Object code = rs.getObject(columnIndex); if (rs.wasNull()) { return null; } return getEnmByCode(code); } @Override public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { Object code = cs.getObject(columnIndex); if (cs.wasNull()) { return null; } return getEnmByCode(code); } private E getEnmByCode(Object code) { if (code == null) { throw new NullPointerException("the result code is null " + code); } if (code instanceof Integer) { for (E e : enums) { if (e.getValue() == code) { return e; } } throw new IllegalArgumentException("Unknown enumeration type , please check the enumeration code : " + code); } if (code instanceof String) { for (E e : enums) { if (code.equals(e.getValue())) { return e; } } throw new IllegalArgumentException("Unknown enumeration type , please check the enumeration code : " + code); } throw new IllegalArgumentException("Unknown enumeration type , please check the enumeration code : " + code); } } ``` 3. 报错信息 2020-01-20 02:45:35.879 ERROR 2472 --- [nio-8081-exec-1] c.l.exception.RRExceptionHandler : nested exception is org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'status' from result set. Cause: java.lang.IllegalArgumentException: No enum constant com.xxx.common.module.enums.StatusEnum.1 * org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'status' from result set. Cause: java.lang.IllegalArgumentException: No enum constant com.xxx.common.module.enums.StatusEnum.1 * at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77) * at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446) * at com.sun.proxy.$Proxy132.selectList(Unknown Source) * at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230) * at com.baomidou.mybatisplus.core.override.PageMapperMethod.executeForMany(PageMapperMethod.java:173) * at com.baomidou.mybatisplus.core.override.PageMapperMethod.execute(PageMapperMethod.java:86) * at com.baomidou.mybatisplus.core.override.PageMapperProxy.invoke(PageMapperProxy.java:64) * at com.sun.proxy.$Proxy137.selectList(Unknown Source) * at com.baomidou.mybatisplus.extension.service.impl.ServiceImpl.getOne(ServiceImpl.java:259) * at com.baomidou.mybatisplus.extension.service.IService.getOne(IService.java:230) * at com.xxx.common.module.service.impl.AppServiceImpl.queryByAppKey(AppServiceImpl.java:100) * at com.xxx.common.module.service.impl.AppServiceImpl$$FastClassBySpringCGLIB$$9380a940.invoke(<generated>) * at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) * at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:684) * at com.xxx.common.module.service.impl.AppServiceImpl$$EnhancerBySpringCGLIB$$307b01.queryByAppKey(<generated>) * at com.xxx.common.module.service.impl.AppInfoServiceImpl.validateBaseApi(AppInfoServiceImpl.java:141) * at com.xxx.common.module.service.impl.AppInfoServiceImpl.appInfo(AppInfoServiceImpl.java:157) * at com.xxx.common.module.service.impl.AppInfoServiceImpl$$FastClassBySpringCGLIB$$2bb67632.invoke(<generated>) * at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) * at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:684) * at com.xxx.common.module.service.impl.AppInfoServiceImpl$$EnhancerBySpringCGLIB$$8bd88917.appInfo(<generated>) * at com.xxx.controller.ApiAppProductController.list(ApiAppProductController.java:79) * at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) * at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) * at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) * at java.lang.reflect.Method.invoke(Method.java:483) * at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) * at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) * at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) * at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) * at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) * at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) * at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) * at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) * at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) * at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908) * at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) * at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) * at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) * at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) * at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) * at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) * at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) * at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) * at com.xxx.common.xss.XssFilter.doFilter(XssFilter.java:24) * at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) * at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) * at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) * at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) * at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) * at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) * at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) * at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) * at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) * at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) * at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) * at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) * at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) * at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) * at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) * at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) * at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) * at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) * at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) * at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) * at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) * at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) * at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) * at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) * at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) * at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) * at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) * at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834) * at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417) * at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) * at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) * at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) * at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) * at java.lang.Thread.run(Thread.java:745) * Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'status' from result set. Cause: java.lang.IllegalArgumentException: No enum constant com.xxx.common.module.enums.StatusEnum.1 * at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:68) * at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.applyAutomaticMappings(DefaultResultSetHandler.java:520) * at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue(DefaultResultSetHandler.java:401) * at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap(DefaultResultSetHandler.java:355) * at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValues(DefaultResultSetHandler.java:330) * at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet(DefaultResultSetHandler.java:303) * at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(DefaultResultSetHandler.java:196) * at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:64) * at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79) * at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) * at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) * at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) * at java.lang.reflect.Method.invoke(Method.java:483) * at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:63) * at com.sun.proxy.$Proxy200.query(Unknown Source) * at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63) * at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:326) * at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) * at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:136) * at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) * at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) * at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) * at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) * at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) * at java.lang.reflect.Method.invoke(Method.java:483) * at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433) * ... 77 common frames omitted * Caused by: java.lang.IllegalArgumentException: No enum constant com.xxx.common.module.enums.StatusEnum.1 * at java.lang.Enum.valueOf(Enum.java:238) * at org.apache.ibatis.type.EnumTypeHandler.getNullableResult(EnumTypeHandler.java:49) * at org.apache.ibatis.type.EnumTypeHandler.getNullableResult(EnumTypeHandler.java:26) * at org.apache.ibatis.type.BaseTypeHandler.getResult(BaseTypeHandler.java:66) * ... 102 common frames omitted
spring&ibatis事务配置问题
xml配置 [code="xml"] <!-- 默认的数据源配置 --> <bean id="talent.defaultDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.default.driverClassName}" /> <property name="url" value="${jdbc.default.url}" /> <property name="username" value="${jdbc.default.username}" /> <property name="password" value="${jdbc.default.password}" /> </bean> <!-- 事务配置 --> <bean id="talent.defaultTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="talent.defaultDataSource" /> </bean> <!-- 配置事务特性 --> <tx:advice id="txAdvice" transaction-manager="talent.defaultTransactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="del*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="main*" propagation="REQUIRED" /> <tx:method name="*" read-only="true" /> </tx:attributes> </tx:advice> <!-- 配置哪些类的方法需要进行事务管理 --> <aop:config> <aop:pointcut id="allManagerMethod" expression="execution(* com.jstrd.talent.manager.MyTransactionTemplate.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" /> </aop:config> <!-- 默认的DaoFactory --> <bean id="talent.defaultDaoFactory" class="com.jstrd.talent.dao.DaoFactory"> <constructor-arg value="${jdbc.default.db.dialect}" /> </bean> <!-- 默认的SqlMapClient --> <bean id="talent.defaultSqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="dataSource" ref="talent.defaultDataSource" /> <property name="configLocation" value="classpath:talent/ibatis/sql-map-config.xml" /> <!-- 自动加载sql-mapping文件 --> <property name="mappingLocations"> <value>${ibatis.mappingLocations}</value> </property> <property name="useTransactionAwareDataSource" value="true"></property> </bean> <!-- 默认的SqlMapDao --> <bean id="talent.defaultSqlMapDao" class="com.jstrd.talent.dao.SqlMapDao"> <property name="sqlMapClient" ref="talent.defaultSqlMapClient" /> </bean> <!-- 默认的SqlMapClientTemplate --> <bean id="talent.defaultSqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient" ref="talent.defaultSqlMapClient" /> </bean> [/code] java代码 [code="java"] public class MyTransactionTemplate { public void addXX() throws Exception { SqlMapDao dao = DaoFactory.getSqlMapDao(); SqlMapClientTemplate sqlMap = dao.getSqlMapClientTemplate();//dao.getSqlMapClientTemplate();//(SqlMapClientTemplate)BeanFactory.getBean("talent.defaultSqlMapClientTemplate"); sqlMap.update("t_user.delete"); sqlMap.update("t_user.insert", new TUser(29, "tan29")); sqlMap.update("t_user.insert", new TUser(30, "tan30")); sqlMap.update("t_user.insert", new TUser(32, "tan32")); sqlMap.update("t_user.updateById", new TUser(29, "tan30"));//这里违反唯一约束,会抛异常的 sqlMap.update("t_user.updateById", new TUser(29, "tan28")); } } [/code] java代码中,连续几个insert,然后两上update,其中一个update是会抛异常的。但是发现前面的insert已经在数据库中生效了,并不回滚 [b]问题补充:[/b] 数据库是mysql5 "MyTransactionTemplate根本没有处于事务中啊"??已经配置在其中了的: execution(* com.jstrd.talent.manager.MyTransactionTemplate.*(..))" [b]问题补充:[/b] 谢谢kyo100900的回答!我改成InnoDb后,事务还是没控制住, 日志发现sqlMap.update()每次都会 Fetching JDBC Connection from DataSource 然后 Returning JDBC Connection to DataSource 这里可能也有问题?! [b]问题补充:[/b] 换了oracle环境还是一样,我怀疑是配错了 [b]问题补充:[/b] xml配置 <pre name="code" class="xml"> &lt;!-- 默认的数据源配置 --> &lt;bean id="talent.defaultDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> &lt;property name="driverClassName" value="${jdbc.default.driverClassName}" /> &lt;property name="url" value="${jdbc.default.url}" /> &lt;property name="username" value="${jdbc.default.username}" /> &lt;property name="password" value="${jdbc.default.password}" /> &lt;/bean> &lt;!-- 事务配置 --> &lt;bean id="talent.defaultTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> &lt;property name="dataSource" ref="talent.defaultDataSource" /> &lt;/bean> &lt;!-- 配置事务特性 --> &lt;tx:advice id="txAdvice" transaction-manager="talent.defaultTransactionManager"> &lt;tx:attributes> &lt;tx:method name="add*" propagation="REQUIRED" /> &lt;tx:method name="save*" propagation="REQUIRED" /> &lt;tx:method name="insert*" propagation="REQUIRED" /> &lt;tx:method name="del*" propagation="REQUIRED" /> &lt;tx:method name="update*" propagation="REQUIRED" /> &lt;tx:method name="main*" propagation="REQUIRED" /> &lt;tx:method name="*" read-only="true" /> &lt;/tx:attributes> &lt;/tx:advice> &lt;!-- 配置哪些类的方法需要进行事务管理 --> &lt;aop:config> &lt;aop:pointcut id="allManagerMethod" expression="execution(* com.jstrd.talent.manager.MyTransactionTemplate.*(..))" /> &lt;aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" /> &lt;/aop:config> &lt;!-- 默认的DaoFactory --> &lt;bean id="talent.defaultDaoFactory" class="com.jstrd.talent.dao.DaoFactory"> &lt;constructor-arg value="${jdbc.default.db.dialect}" /> &lt;/bean> &lt;!-- 默认的SqlMapClient --> &lt;bean id="talent.defaultSqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> &lt;property name="dataSource" ref="talent.defaultDataSource" /> &lt;property name="configLocation" value="classpath:talent/ibatis/sql-map-config.xml" /> &lt;!-- 自动加载sql-mapping文件 --> &lt;property name="mappingLocations"> &lt;value>${ibatis.mappingLocations}&lt;/value> &lt;/property> &lt;property name="useTransactionAwareDataSource" value="true">&lt;/property> &lt;/bean> &lt;!-- 默认的SqlMapDao --> &lt;bean id="talent.defaultSqlMapDao" class="com.jstrd.talent.dao.SqlMapDao"> &lt;property name="sqlMapClient" ref="talent.defaultSqlMapClient" /> &lt;/bean> &lt;!-- 默认的SqlMapClientTemplate --> &lt;bean id="talent.defaultSqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> &lt;property name="sqlMapClient" ref="talent.defaultSqlMapClient" /> &lt;/bean> </pre> java代码 <pre name="code" class="java"> public class MyTransactionTemplate { public void addXX() throws Exception { SqlMapDao dao = DaoFactory.getSqlMapDao(); SqlMapClientTemplate sqlMap = dao.getSqlMapClientTemplate();//dao.getSqlMapClientTemplate();//(SqlMapClientTemplate)BeanFactory.getBean("talent.defaultSqlMapClientTemplate"); sqlMap.update("t_user.delete"); sqlMap.update("t_user.insert", new TUser(29, "tan29")); sqlMap.update("t_user.insert", new TUser(30, "tan30")); sqlMap.update("t_user.insert", new TUser(32, "tan32")); sqlMap.update("t_user.updateById", new TUser(29, "tan30"));//这里违反唯一约束,会抛异常的 sqlMap.update("t_user.updateById", new TUser(29, "tan28")); } } </pre> java代码中,连续几个insert,然后两上update,其中一个update是会抛异常的。但是发现前面的insert已经在数据库中生效了,并不回滚 <strong>问题补充:</strong> 数据库是mysql5 "MyTransactionTemplate根本没有处于事务中啊"??已经配置在其中了的: execution(* com.jstrd.talent.manager.MyTransactionTemplate.*(..))" <strong>问题补充:</strong> 谢谢kyo100900的回答!我改成InnoDb后,事务还是没控制住, 日志发现sqlMap.update()每次都会 Fetching JDBC Connection from DataSource 然后 Returning JDBC Connection to DataSource 这里可能也有问题?! <strong>问题补充:</strong> 换了oracle环境还是一样,我怀疑是配错了 调试发现SqlMapClientTemplate的事务管理器为com.ibatis.sqlmap.engine.transaction.TransactionManager@19f9c7a.跟配置的不一样啊 [b]问题补充:[/b] "MyTransactionTemplate根本没有处于事务中啊"??已经配置在其中了的: execution(* com.jstrd.talent.manager.MyTransactionTemplate.*(..))" &lt;strong>问题补充:&lt;/strong> 谢谢kyo100900的回答!我改成InnoDb后,事务还是没控制住, 日志发现sqlMap.update()每次都会 Fetching JDBC Connection from DataSource 然后 Returning JDBC Connection to DataSource 这里可能也有问题?! &lt;strong>问题补充:&lt;/strong> 换了oracle环境还是一样,我怀疑是配错了 调试发现SqlMapClientTemplate的事务管理器为com.ibatis.sqlmap.engine.transaction.TransactionManager@19f9c7a.跟配置的不一样啊
spring+ibatis配置问题
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"> <value>oracle.jdbc.driver.OracleDriver</value> </property> <property name="url"> <value>jdbc:oracle:thin:@localhost:1521:yssf</value> </property> <property name="username"> <value>sa</value> </property> <property name="password"> <value>sa</value> </property> </bean> <bean id="sqlMapClient" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="dataSource"> <ref bean="ds"/> </property> <property name="configLocation"> <value>WEB-INF/sql-map-config.xml</value> </property> </bean> 报错如下: javax.servlet.ServletException: Error creating bean with name 'sqlMapClient' defined in class path resource [applicationContext.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'dataSource' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'dataSource' is not writable or has an invalid setter method: Does the parameter type of the setter match the return type of the getter? org.apache.struts.action.RequestProcessor.processException(RequestProcessor.java:545) org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:486) org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274) org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482) org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507) javax.servlet.http.HttpServlet.service(HttpServlet.java:743) javax.servlet.http.HttpServlet.service(HttpServlet.java:856) 期待高手解决下。 [b]问题补充:[/b] 还是不行啊,Error parsing XML. Cause: org.xml.sax.SAXParseException: Document root element "sqlMapConfig", must match DOCTYPE root "null". [b]问题补充:[/b] <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <sqlMap resource="vo/User.xml"/> </sqlMapConfig> User.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd"> <sqlMap namespace="User"> <resultMap id="result" class="vo.User"> <result property="id" column="id" /> <result property="name" column="username" /> <result property="password" column="password" /> </resultMap> <statement id="getUserByName" resultMap="result"> select * from user where username=#name# </statement> </sqlMap>
spring+iBatis的xml解析问题
使用Spring+iBatis开发,测试是发生如下异常,百思不得其解啊!求高人指点 `Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlMapClient' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse config resource: class path resource [sql-map-config.xml]; nested exception is com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: org.xml.sax.SAXParseException; lineNumber: 2; columnNumber: 1; 文件提前结束。` 以下是我的代码 **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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/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"> <!-- lob字段配置 --> <bean id="nativeJdbcExtractor" lazy-init="true" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" /> <!-- class="org.springframework.jdbc.support.nativejdbc.WebSphereNativeJdbcExtractor" /> --> <bean id="lobHandler" lazy-init="true" class="org.springframework.jdbc.support.lob.OracleLobHandler"> <property name="nativeJdbcExtractor"> <ref bean="nativeJdbcExtractor" /> </property> </bean> <!-- 加载系统数据源配置文件 --> <!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>org.logicalcobwebs.proxool.ProxoolDriver </value> </property> <property name="url"> <value>proxool.cloud</value> </property> </bean> --> <!-- ******************************************************************** --> <!--WEB-INF/classes/ --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="jdbc.properties" /> <property name="fileEncoding" value="UTF-8" /> </bean> <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <!-- <property name="driver"> <value>com.mysql.jdbc.Driver</value> </property> <property name="driverUrl"> <value>jdbc:mysql://localhost/mytest?characterEncoding=utf-8</value> </property> --> <property name="driver"> <value>${jdbc.driver}</value> </property> <property name="driverUrl"> <value>${jdbc.url}</value> </property> <property name="user"> <value>${jdbc.username}</value> </property> <property name="password"> <value>${jdbc.password}</value> </property> <!-- <property name="user"> <value>root</value> </property> <property name="password"> <value>root</value> </property> --> <property name="alias"> <value>wstudy</value> </property> <property name="houseKeepingSleepTime"> <value>60000</value> </property> <property name="prototypeCount"> <value>5</value> </property> <property name="simultaneousBuildThrottle"> <value>20</value> </property> <property name="maximumActiveTime"> <value>60000</value> </property> <property name="houseKeepingTestSql"> <value>select CURRENT_DATE</value> </property> <property name="maximumConnectionCount"> <value>10</value> </property> <property name="minimumConnectionCount"> <value>1</value> </property> <property name="trace"> <value>true</value> </property> <property name="verbose"> <value>true</value> </property> </bean> <!-- *************************************************************************** --> <!-- 事务管理 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <!-- 事务通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" propagation="REQUIRED" timeout="60" rollback-for="Exception"/> <tx:method name="add*" propagation="REQUIRED" timeout="60" rollback-for="Exception"/> <tx:method name="delete*" propagation="REQUIRED" timeout="60" rollback-for="Exception"/> <tx:method name="modify*" propagation="REQUIRED" timeout="60" rollback-for="Exception"/> <tx:method name="save*" propagation="REQUIRED" timeout="60" rollback-for="Exception"/> <tx:method name="insert*" propagation="REQUIRED" timeout="60" rollback-for="Exception"/> <tx:method name="update*" propagation="REQUIRED" timeout="60" rollback-for="Exception"/> <tx:method name="*" read-only="true" timeout="60"/> </tx:attributes> </tx:advice> <!-- WEB-INF/classes/ --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocations" value="sql-map-config.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient"> <ref bean="sqlMapClient" /> </property> </bean> <bean id="baseDao" class="com.wstudy.core.dao.BaseDaoImpl"> <property name="sqlMapClientTemplate"> <ref bean="sqlMapClientTemplate" /> </property> </bean> <!--将上面的模版类织入到我们的DAO对象中 --> <bean id="studentDao" class="test.ibatis.StudentDao"> <property name="sqlMapClientTemplate"> <ref bean="sqlMapClientTemplate" /> </property> </bean> <bean id="stDao" class="com.wstudy.dao.impl.StudentDaoImpl" parent="baseDao" scope="prototype"> </bean> <!-- <bean id="dbtest" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref local="dataSource" /> </property> </bean> --> <!-- 小柴的beans开始 --> <!-- 导入其他配置模块 --> <import resource="com/wstudy/questions/service/Question.xml" /> <!-- 导入其他配置模块 --> <import resource="com/wstudy/service/teacher/teacher.xml" /> </beans> **sql-map-config.xml:** <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <settings cacheModelsEnabled="true" enhancementEnabled="true" lazyLoadingEnabled="true" errorTracingEnabled="true" maxRequests="50" maxSessions="10" maxTransactions="5" useStatementNamespaces="true" /> <!-- <sqlMap resource="com/wstudy/test/AdminUserEntity.xml" /> --> <sqlMap resource="com/wstudy/entity/teacher/TeacherEntity.xml" /> <sqlMap resource="com/wstudy/entity/teacher/EvaluationEntity.xml" /> <sqlMap resource="com/wstudy/entity/teacher/TeacherStarEntity.xml" /> <sqlMap resource="com/wstudy/entity/teacher/QueAnsEntity.xml" /> <sqlMap resource="com/wstudy/entity/teacher/EvaTeacherEntity.xml" /> <sqlMap resource="com/wstudy/core/entity/StudentEntity.xml" /> <sqlMap resource="test/ibatis/Student.xml" /> <sqlMap resource="com/wstudy/questions/entity/ComQuesAnsEntity.xml" /> <sqlMap resource="com/wstudy/questions/entity/ComQuesEntity.xml" /> <sqlMap resource="com/wstudy/questions/entity/TypicalQuesEntity.xml" /> </sqlMapConfig>
关于struts2 spring ibatis 结合问题
这2天 在学习IBATIS 准备写一个 struts hibernate ibatis 的例子出来 但是一直就没成功 我说一下我的配置步骤,请大家帮我指点一下我哪里错了 1.首先我在WEB.XML文件里 加入 STRUTS2的主控制器 <!-- struts2 主控制器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 2.然后添加SPRING支持 <!-- 设置Spring框架配置文件路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:applicationContext*.xml </param-value> </context-param> <!-- 整合Spring框架 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> 3.在classpath 下创建 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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/test</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> </bean> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation"> <value>classpath:SqlMapConfig.xml</value> </property> <property name="dataSource"> <ref local="dataSource" /> </property> </bean> <!-- 配置事务特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> <!-- 配置那些类的方法进行事务管理 --> <aop:config> <aop:pointcut id="allManagerMethod" expression="execution(* org.fire.inoutstock.service.*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod" /> </aop:config> </beans> 然后在classpath下创建 sqlmapclient.xml文件 文件内容 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <sqlMap resource="sqlMap.T_User.xml" /> </sqlMapConfig> 我就这样搭建的, 然后跑的时候出错 错误信息如下 2009-6-30 12:36:33 org.apache.catalina.core.StandardContext listenerStart 严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlMapClient' defined in file [D:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\test2\WEB-INF\classes\applicationContext-common.xml]: Invocation of init method failed; nested exception is com.ibatis.common.exception.NestedRuntimeException: Error occurred. Cause: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1336) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:471) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:220) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4350) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:924) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:887) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1147) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:578) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: com.ibatis.common.exception.NestedRuntimeException: Error occurred. Cause: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser.parse(SqlMapConfigParser.java:81) at com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(SqlMapClientBuilder.java:62) at org.springframework.orm.ibatis.SqlMapClientFactoryBean.buildSqlMapClient(SqlMapClientFactoryBean.java:329) at org.springframework.orm.ibatis.SqlMapClientFactoryBean.afterPropertiesSet(SqlMapClientFactoryBean.java:280) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1367) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1333) ... 39 more Caused by: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:53) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser.parse(SqlMapConfigParser.java:78) ... 44 more Caused by: com.ibatis.common.exception.NestedRuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource sqlMap.T_User.xml Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml at com.ibatis.common.xml.NodeletParser.processNodelet(NodeletParser.java:114) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:75) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:93) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:63) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:51) ... 45 more Caused by: java.io.IOException: Could not find resource sqlMap.T_User.xml at com.ibatis.common.resources.Resources.getResourceAsStream(Resources.java:101) at com.ibatis.common.resources.Resources.getResourceAsStream(Resources.java:86) at com.ibatis.common.resources.Resources.getResourceAsReader(Resources.java:150) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser$11.process(SqlMapConfigParser.java:336) at com.ibatis.common.xml.NodeletParser.processNodelet(NodeletParser.java:112) ... 49 more 2009-6-30 12:36:33 org.apache.catalina.core.StandardContext start 严重: Error listenerStart 2009-6-30 12:36:33 org.apache.catalina.core.StandardContext start 严重: Context [/test2] startup failed due to previous errors 2009-6-30 12:36:33 org.apache.catalina.core.ApplicationContext log 就这样我没成功 我导入的包有 ibatis-common-2.jar ibatis-sqlmap-2.jar ibatis-dao-2.jar 其他的包都和是STRUTS 和SPRING 还有其他的包了 请教大家帮我看看那里有问题 最好能总结一下 struts2 spring ibatis 搭建的步骤和相关的 JAR包 [b]问题补充:[/b] 还有一个问题。。。 就是ibatis 不能用spring 的aop来管理事物吗? 如果能的话要怎样来写?? <!-- 配置事务特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" /> </tx:attributes> </tx:advice> 提示创建txAdvice错误 错误信息 Error creating bean with name 'txAdvice': Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined 谢谢PURAS 刚才的回答。。
idea启动控制台报错Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl,求助
改了一处xml,启动后一直报Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl,后来把代码还原了还是报同样的错误,求助
这个 Bug 搞了一个星期了没弄好,崩溃重,哪位大佬能帮忙看看??
控制台信息:![图片说明](https://img-ask.csdn.net/upload/202001/18/1579336366_42087.jpg) ``` org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Access denied for user 'koison'@'localhost' (using password: YES)) ### The error may exist in file [/Users/koison/IdeaProjects/selfOA/target/oasys/WEB-INF/classes/mapper/UserDao.xml] ### The error may involve com.gcc.dao.UserDao.findByUsername ### The error occurred while executing a query ### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Access denied for user 'koison'@'localhost' (using password: YES)) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) javax.servlet.http.HttpServlet.service(HttpServlet.java:660) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ```
spring升级到4.x后,orm包里面移除了对ibatis的支持,这是为什么
spring升级到4.x后,orm包里面移除了对ibatis的支持,这是为什么
ruby on rails服务器与springMVC spring ibatis服务器间怎么通信
有两个web服务器: 1.ruby on rails搭建的 2.springMVC spring ibatis搭建的 怎么实现: 请求ruby服务器,然后通过ruby 重定向到java服务器,再然后java服务器将处理完的数据重新发给ruby服务器,最后由ruby将数据响应给浏览器。 望大牛给个详细的方案,谢谢!
ibatis+spring mvc事务不能回滚
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <p>最近才接触spring MVC和ibates,现在我需要配置事务回滚,但是倒腾了一天还是不行,熟悉的朋友帮忙看看: applicationContext.xml文件配置:</p> <p> </p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd" default-autowire="byName"&gt; &lt;context:component-scan base-package="com.suneee"&gt; &lt;context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/&gt; &lt;/context:component-scan&gt; &lt;bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="location"&gt; &lt;value&gt;classpath:com/suneee/config/mysql/jdbc.properties&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"&gt; &lt;property name="driverClassName" value="${db.driverClassName}"/&gt; &lt;property name="url" value="${db.url}"/&gt; &lt;property name="username" value="${db.username}"/&gt; &lt;property name="password" value="${db.password}"/&gt; &lt;/bean&gt; &lt;!-- 配置数据源 --&gt; &lt;bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;property name="configLocation"&gt; &lt;value&gt;classpath:com/suneee/config/ibatis/SqlMapConfig.xml&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;!-- 配置事务管理器 --&gt; &lt;bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;/bean&gt; &lt;!-- 配置哪些类的方法需要进行事务管理 proxy-target-class="true" --&gt; &lt;aop:config &gt; &lt;aop:pointcut id="crudMethos" expression="execution(* com.suneee.service.*.*(..))"/&gt; &lt;aop:advisor advice-ref="txAdvice" pointcut-ref="crudMethos" /&gt; &lt;/aop:config&gt; &lt;!--配置哪些方法,什么情况下需要回滚--&gt; &lt;tx:advice id="txAdvice" transaction-manager="transactionManager"&gt; &lt;tx:attributes&gt; &lt;tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception"/&gt; &lt;tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception"/&gt; &lt;tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception"/&gt; &lt;!-- &lt;tx:method name="*" propagation="REQUIRED" read-only="true"/&gt; --&gt; &lt;!-- 除了上面标识的方法,其他方法全是只读方法 --&gt; &lt;/tx:attributes&gt; &lt;/tx:advice&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p>springMVC.XML文件内容如下:</p> <p> </p> <pre name="code" class="java">&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 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" default-autowire="byName"&gt; &lt;!-- 自动扫描的包名 --&gt; &lt;context:component-scan base-package="com.suneee"&gt; &lt;context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/&gt; &lt;/context:component-scan&gt; &lt;!-- 视图解释类 --&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/WEB-INF/jsp/"&gt;&lt;/property&gt; &lt;property name="suffix" value=".jsp"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&gt; &lt;/bean&gt; &lt;!-- 拦截器 &lt;mvc:interceptors&gt; &lt;mvc:interceptor&gt; &lt;mvc:mapping path="/*.do"/&gt; &lt;bean class="com.suneee.interceptor.MyInterceptor"&gt;&lt;/bean&gt; &lt;/mvc:interceptor&gt; &lt;/mvc:interceptors&gt; --&gt; &lt;/beans&gt;</pre> <p> </p> <p> </p> <p>UserService.java内容如下:</p> <p> </p> <pre name="code" class="java">package com.suneee.service.impl; import java.util.List; import org.springframework.stereotype.Service; import com.suneee.bean.User; import com.suneee.service.IUserService; import com.suneee.service.base.BaseService; @Service("userService") public class UserService extends BaseService&lt;User&gt; implements IUserService{ @Override public List&lt;User&gt; findUser(User user) { return queryForList("user_queryAll",user); } @Override public User insert(User user){ insert("user_insert",user); user = null;//故意设置为null,抛出异常 insert("user_inserts",user); return user; } } </pre> <p> </p> <p> </p> <p>BaseService.java文件如下:</p> <pre name="code" class="java">package com.suneee.service.base; import java.sql.SQLException; import java.util.List; import org.springframework.orm.ibatis.SqlMapClientTemplate; public class BaseService&lt;T&gt; extends SqlMapClientTemplate{ public static final int PAGE_SIZE = 15; public Object insert(String sqlId,Object baseClass){ Object baseClassResult = null; try { baseClassResult = (Object) super.getSqlMapClient().insert(sqlId,baseClass); } catch (SQLException e) { e.printStackTrace(); } return baseClassResult; } public Object queryForObject(String sqlId,Object baseClass){ Object baseClassResult = null; try { baseClassResult = (Object) super.getSqlMapClient().queryForObject(sqlId,baseClass); } catch (SQLException e) { e.printStackTrace(); } return baseClassResult; } public Integer delete(String sqlId,Integer id){ Integer number = null; try { number = super.getSqlMapClient().delete(sqlId, id); } catch (SQLException e) { e.printStackTrace(); } return number; } public Integer deleteByObject(String sqlId,Object obj){ Integer number = null; try { number = super.getSqlMapClient().delete(sqlId, obj); } catch (SQLException e) { e.printStackTrace(); } return number; } public Object queryById(String sqlId,Integer id){ Object baseClassResult = null; try { baseClassResult = (Object) super.getSqlMapClient().queryForObject(sqlId,id); } catch (SQLException e) { e.printStackTrace(); } return baseClassResult; } public List&lt;Object&gt; queryListByPage(String sqlId,Object obj){ List&lt;Object&gt; list = null; try { list = (List&lt;Object&gt;) super.getSqlMapClient().queryForList(sqlId, obj); } catch (SQLException e) { e.printStackTrace(); } return list; } public List&lt;Object&gt; queryListNoPage(String sqlId,Object obj){ List&lt;Object&gt; list = null; try { list = (List&lt;Object&gt;) super.getSqlMapClient().queryForList(sqlId, obj); } catch (SQLException e) { e.printStackTrace(); } return list; } public int update(String sqlId,Object obj){ Integer number = null; try { number = super.getSqlMapClient().update(sqlId, obj); } catch (SQLException e) { e.printStackTrace(); } return number; } //批量入库 public boolean insertBatch(String sqlId,List list){ Object obj = null; try { super.getSqlMapClient().startBatch(); for(int i=0; i&lt;list.size(); i++){ obj = list.get(i); super.getSqlMapClient().insert(sqlId,obj); } super.getSqlMapClient().executeBatch(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } public int getCount(String sqlId){ Integer i = null; try { i = (Integer) super.getSqlMapClient().queryForObject(sqlId); } catch (SQLException e) { e.printStackTrace(); } return i; } }</pre> <p> </p> <p> </p> <p>以上就是我项目各个地方的代码,第二个插入数据方法我故意设置为null,执行报错,但是第一个插入数据方法执行了数据插入,没有回滚,怎样才能回滚啊,声明式的事务配置有错还是什么原因,熟悉的兄弟看看,困扰了我一天多了</p> </div>
Spring2.5 ibatis 配置问题
一个很菜的问题,困扰我很久了.在SpringSide3中配置ibatis,始终不成功,提示 [code="java"]Property 'sqlMapClient' is required[/code] applicationContext.xml代码如下: [code="xml"] <!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 (多个包可以以逗号分隔)--> <context:component-scan base-package="jp.co.grids.mda" /> <!-- 数据源配置,在开发测试环境直连数据库 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@192.168.2.120:1521:MDA" /> <property name="username" value="MDA1" /> <property name="password" value="MDA" /> </bean> <!-- 事务管理器配置,单数据源事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="classpath:/dao/sql-map-config.xml"/> <property name="dataSource" ref="dataSource"/> </bean> <!-- 使用annotation定义事务 --> <tx:annotation-driven transaction-manager="transactionManager" /> <!-- 默认的SqlMapClientTemplate --> <bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate"> <property name="sqlMapClient" ref="sqlMapClient" /> </bean> <bean id="entityDao" class="jp.co.grids.mda.base.EntityDao"> <property name="dataSource"> <ref local="dataSource"/> </property> <property name="sqlMapClient" ref="sqlMapClient" /> </bean> <bean id="userDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager" /> </property> <property name="target"> <ref bean="entityDao" /> </property> </bean>[/code] 其中的EntityDao继承自GenericDao,GenericDao才继承自SqlMapClientDaoSupport.会不会是这个的问题?
struts+spring +ibatis实现上传功能的代码
求struts+spring +ibatis实现上传功能的代码
maven spring和ibatis的整合遇到的问题
下面两个是我的spring-ibatis的整合,另一个是sqlmapconfig.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: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/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 "> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="2" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="1" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <property name="filters" value="mergeStat" /> </bean> **strong text** **<!-- ibatis sqlMapClient 配置 让spring来管理SqlMapClient对象--> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="classpath:sqlmapconfig.xml"/> <property name="dataSource" ref="dataSource"/> </bean>** <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 注解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* hyl.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> <!-- 配置druid监控spring jdbc --> <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> </bean> <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype"> <property name="patterns"> <list> <value>hyl.service.*</value> </list> </property> </bean> <aop:config> <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" /> </aop:config> </beans> 这是sqlmapconfig.xml的配置 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <sqlMap resource="classpath:hyl/sqlMap/TUSER_SqlMap.xml" /> </sqlMapConfig> 加粗的是后台提示的错误,嵌套错误:下面是错误的提示 [org.springframework.context.support.ClassPathXmlApplicationContext]Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@bfea1d: startup date [Thu Jan 16 17:17:54 CST 2014]; root of context hierarchy [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]Loading XML bean definitions from class path resource [spring.xml] [org.springframework.beans.factory.xml.XmlBeanDefinitionReader]Loading XML bean definitions from class path resource [spring-ibatis.xml] [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer]Loading properties file from class path resource [config.properties] [org.springframework.beans.factory.support.DefaultListableBeanFactory]Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1bbd7b2: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,dataSource,sqlMapClient,transactionManager,transactionAdvice,org.springframework.aop.config.internalAutoProxyCreator,transactionPointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,druid-stat-interceptor,druid-stat-pointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#1,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy [com.alibaba.druid.pool.DruidAbstractDataSource]maxIdle is deprecated [com.alibaba.druid.pool.DruidDataSource]{dataSource-1} inited [org.springframework.beans.factory.support.DefaultListableBeanFactory]Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1bbd7b2: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,dataSource,sqlMapClient,transactionManager,transactionAdvice,org.springframework.aop.config.internalAutoProxyCreator,transactionPointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0,druid-stat-interceptor,druid-stat-pointcut,org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#1,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy [com.alibaba.druid.pool.DruidDataSource]{dataSource-1} closed Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlMapClient' defined in class path resource [spring-ibatis.xml]: Invocation of init method failed; nested exception is org.springframework.core.NestedIOException: Failed to parse config resource: class path resource [sqlmapconfig.xml]; nested exception is com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:591) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93) at hyl.test.Test.main(Test.java:13) Caused by: org.springframework.core.NestedIOException: Failed to parse config resource: class path resource [sqlmapconfig.xml]; nested exception is com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at org.springframework.orm.ibatis.SqlMapClientFactoryBean.buildSqlMapClient(SqlMapClientFactoryBean.java:341) at org.springframework.orm.ibatis.SqlMapClientFactoryBean.afterPropertiesSet(SqlMapClientFactoryBean.java:291) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452) ... 12 more Caused by: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:62) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser.parse(SqlMapConfigParser.java:62) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser.parse(SqlMapConfigParser.java:55) at org.springframework.orm.ibatis.SqlMapClientFactoryBean.buildSqlMapClient(SqlMapClientFactoryBean.java:338) ... 15 more Caused by: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at com.ibatis.common.xml.NodeletParser.processNodelet(NodeletParser.java:123) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:84) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:102) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:72) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:60) ... 18 more Caused by: java.io.IOException: Could not find resource classpath:hyl/sqlMap/TUSER_SqlMap.xml at com.ibatis.common.resources.Resources.getResourceAsStream(Resources.java:110) at com.ibatis.common.resources.Resources.getResourceAsStream(Resources.java:95) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser$10.process(SqlMapConfigParser.java:249) at com.ibatis.common.xml.NodeletParser.processNodelet(NodeletParser.java:121) ... 22 more 下面的是我TUSER_SqlMap.xml文件 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" > <sqlMap namespace="TUSER" > <resultMap id="BaseResultMap" class="hyl.model.Tuser" > <result column="ID" property="id" jdbcType="VARCHAR" /> <result column="NAME" property="name" jdbcType="VARCHAR" /> <result column="PWD" property="pwd" jdbcType="VARCHAR" /> <result column="CREATEDATATIME" property="createdatatime" jdbcType="DATE" /> <result column="MODIFYDATATIME" property="modifydatatime" jdbcType="DATE" /> </resultMap> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterClass="hyl.model.Tuser" > select ID, NAME, PWD, CREATEDATATIME, MODIFYDATATIME from TUSER where ID = #id:VARCHAR# </select> <delete id="deleteByPrimaryKey" parameterClass="hyl.model.Tuser" > delete from TUSER where ID = #id:VARCHAR# </delete> <insert id="insert" parameterClass="hyl.model.Tuser" > insert into TUSER (ID, NAME, PWD, CREATEDATATIME, MODIFYDATATIME) values (#id:VARCHAR#, #name:VARCHAR#, #pwd:VARCHAR#, #createdatatime:DATE#, #modifydatatime:DATE#) </insert> <insert id="insertSelective" parameterClass="hyl.model.Tuser" > insert into TUSER <dynamic prepend="(" > <isNotNull prepend="," property="id" > ID </isNotNull> <isNotNull prepend="," property="name" > NAME </isNotNull> <isNotNull prepend="," property="pwd" > PWD </isNotNull> <isNotNull prepend="," property="createdatatime" > CREATEDATATIME </isNotNull> <isNotNull prepend="," property="modifydatatime" > MODIFYDATATIME </isNotNull> ) </dynamic> values <dynamic prepend="(" > <isNotNull prepend="," property="id" > #id:VARCHAR# </isNotNull> <isNotNull prepend="," property="name" > #name:VARCHAR# </isNotNull> <isNotNull prepend="," property="pwd" > #pwd:VARCHAR# </isNotNull> <isNotNull prepend="," property="createdatatime" > #createdatatime:DATE# </isNotNull> <isNotNull prepend="," property="modifydatatime" > #modifydatatime:DATE# </isNotNull> ) </dynamic> </insert> <update id="updateByPrimaryKeySelective" parameterClass="hyl.model.Tuser" > update TUSER <dynamic prepend="set" > <isNotNull prepend="," property="name" > NAME = #name:VARCHAR# </isNotNull> <isNotNull prepend="," property="pwd" > PWD = #pwd:VARCHAR# </isNotNull> <isNotNull prepend="," property="createdatatime" > CREATEDATATIME = #createdatatime:DATE# </isNotNull> <isNotNull prepend="," property="modifydatatime" > MODIFYDATATIME = #modifydatatime:DATE# </isNotNull> </dynamic> where ID = #id:VARCHAR# </update> <update id="updateByPrimaryKey" parameterClass="hyl.model.Tuser" > update TUSER set NAME = #name:VARCHAR#, PWD = #pwd:VARCHAR#, CREATEDATATIME = #createdatatime:DATE#, MODIFYDATATIME = #modifydatatime:DATE# where ID = #id:VARCHAR# </update> </sqlMap> 这个问题困扰我一周了,希望各位能帮助下,若需要我的项目请与我联系:QQ632105841,再次谢谢!
SpringBoot中@Autowired注入bean失败:Error creating bean with name“XXXController”?
# 报错信息: ``` org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authorizeController': Unsatisfied dependency expressed through field 'userMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userMapper' defined in file [E:\STS-WorkSpace\Forum\target\classes\com\Forum\mapper\UserMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:116) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1422) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:594) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$141/1866850137.getObject(Unknown Source) ~[na:na] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:879) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.2.2.RELEASE.jar:2.2.2.RELEASE] at com.Forum.ForumApplication.main(ForumApplication.java:19) [classes/:na] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userMapper' defined in file [E:\STS-WorkSpace\Forum\target\classes\com\Forum\mapper\UserMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory$$Lambda$141/1866850137.getObject(Unknown Source) ~[na:na] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1287) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1207) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:640) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] ... 20 common frames omitted Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required at org.springframework.util.Assert.notNull(Assert.java:198) ~[spring-core-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.mybatis.spring.support.SqlSessionDaoSupport.checkDaoConfig(SqlSessionDaoSupport.java:123) ~[mybatis-spring-2.0.1.jar:2.0.1] at org.mybatis.spring.mapper.MapperFactoryBean.checkDaoConfig(MapperFactoryBean.java:73) ~[mybatis-spring-2.0.1.jar:2.0.1] at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44) ~[spring-tx-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.2.RELEASE.jar:5.2.2.RELEASE] ... 31 common frames omitted ``` # Mapper代码: ``` package com.Forum.mapper; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import com.Forum.Model.User; @Mapper public interface UserMapper{ @Insert("insert into user (name,account_id,token,gmt_create,gmt_modified) values (#{name},#{accountId}),#{token},#{gmtCreate},#{gmtModified}") public void insert(User user); } ``` # 启动代码: ``` package com.Forum; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @ComponentScan(basePackages = {"com.Forum.*"}) @MapperScan(basePackages = {"com.Forum.mapper"}) public class ForumApplication { public static void main(String[] args) { SpringApplication.run(ForumApplication.class, args); } } ``` # Controller代码: ```package com.Forum.Controller; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import com.Forum.Dto.AccesstokenDTO; import com.Forum.Dto.GitHubUser; import com.Forum.Model.User; import com.Forum.Provider.GitHubProvider; import com.Forum.mapper.UserMapper; @Controller public class AuthorizeController{ @Autowired private GitHubProvider gitHubProvider; @Value("${github.client.id}") private String clientId; @Value("${github.client.secret}") private String clientSecret; @Value("${github.redirect.uri}") private String redirectUri; @Autowired public UserMapper userMapper; @GetMapping("/callback") public String callback(@RequestParam(name="code") String code, @RequestParam(name="state") String state, HttpServletRequest request ) { AccesstokenDTO accesstokenDTO = new AccesstokenDTO(); accesstokenDTO.setCode(code); accesstokenDTO.setRedirect_uri("redirectUri"); accesstokenDTO.setClient_id(clientId); accesstokenDTO.setClient_secret(clientSecret); accesstokenDTO.setState(state); String accessToken = gitHubProvider.getAccessToken(accesstokenDTO); GitHubUser githubUser = gitHubProvider.getUser(accessToken); if(githubUser != null) { // 登录成功,写cookie和session User user = new User(); user.setToken(UUID.randomUUID().toString()); user.setName(githubUser.getName()); user.setAccountId(String.valueOf(githubUser.getId())); user.setQmtCreate(System.currentTimeMillis()); user.setQmtModified(user.getQmtCreate()); userMapper.insert(user); request.getSession().setAttribute("user", githubUser); return "redirect:/"; // 去掉地址后缀 }else { // 登录失败,重新登录 return "redirect:/"; } } } ```
ibatis配置问题
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap> <!-- 为Person类设置一个别名 --> <typeAlias alias="user" type="com.lt.ibatis.pojo.user"/> <!-- 配置表和类之间的映射关系 --> <resultMap class="com.lt.ibatis.pojo.user" id="userMap"> <result property="userid" column="userid"/> <result property="username" column="username"/> <result property="password" column="password"/> <result property="phone" column="phone"/> <result property="fax" column="fax"/> </resultMap> <!-- 验证帐号密码 --> <select id="queryAccount" parameterClass="java.lang.String" resultClass="com.lt.ibatis.pojo.User"> <![CDATA[ SELECT * FROM USERTAB WHERE USERID=#USERID# AND PASSWORD=#PASSWORD# ]]> </select> </sqlMap> 这是我的 User.xml 表映射文件  报的错误是: Exception in thread "main" java.lang.NoClassDefFoundError: com/lt/ibatis/pojo/user (wrong name: com/lt/ibatis/pojo/User) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at com.ibatis.common.resources.Resources.classForName(Resources.java:260) at com.ibatis.sqlmap.engine.builder.xml.SqlMapParser$14.process(SqlMapParser.java:374) at com.ibatis.common.xml.NodeletParser.processNodelet(NodeletParser.java:121) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:84) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:102) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:72) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:51) at com.ibatis.sqlmap.engine.builder.xml.SqlMapParser.parse(SqlMapParser.java:51) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser$11.process(SqlMapConfigParser.java:410) at com.ibatis.common.xml.NodeletParser.processNodelet(NodeletParser.java:121) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:84) at com.ibatis.common.xml.NodeletParser.process(NodeletParser.java:102) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:72) at com.ibatis.common.xml.NodeletParser.parse(NodeletParser.java:51) at com.ibatis.sqlmap.engine.builder.xml.SqlMapConfigParser.parse(SqlMapConfigParser.java:86) at com.ibatis.sqlmap.client.SqlMapClientBuilder.buildSqlMapClient(SqlMapClientBuilder.java:63) at com.lt.dao.QuoteDao.queryAccount(QuoteDao.java:19) at com.lt.dao.TestDao.main(TestDao.java:15) 好象是路径问题,本人刚学习ibatis,之前学的一个DEMO都成功了,这次自己写的就出问题了?有人能回答下吗?
spring+ibatis xml 文件的配置问题
applicationContext.xml 里: <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="sqlMapConfig.xml" /> <property name="dataSource" ref="dataSource" /> </bean> sqlMapConfig.xml 跟 applicationContext.xml 是同一个目录下 我都放在src目录下,但是:tomcat 启动时: ontext initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlMapClient' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/sqlMapConfig.xml] 提示 找不到该文件了 但是单位测试的时候是没问题的
spring ibatis weblogic 出错
信息: JDBC 3.0 Savepoint class is available AbandonedObjectPool is used (org.apache.commons.dbcp.AbandonedObjectPool@183fc68) LogAbandoned: true RemoveAbandoned: true RemoveAbandonedTimeout: 180 2008-7-26 21:22:48 org.apache.struts.action.RequestProcessor processException 警告: Unhandled Exception thrown: class com.ibatis.sqlmap.client.SqlMapException <2008-7-26 下午09时22分48秒 CST> <Error> <HTTP> <BEA-101017> <[weblogic.servlet.internal.WebAppServletContext@f353e5 - appName: '_appsdir_ibatis_dir', name: 'ibatis', context-path: ''] Root cause of ServletException. com.ibatis.sqlmap.client.SqlMapException: There is no statement named creatUser in this SqlMap. at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.getMappedStatement(SqlMapExecutorDelegate.java:288) at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.insert(SqlMapExecutorDelegate.java:424) at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.insert(SqlMapSessionImpl.java:81) at com.ibatis.sqlmap.engine.impl.SqlMapClientImpl.insert(SqlMapClientImpl.java:58) at com.ibatis.dao.UserDAOImpl.save(UserDAOImpl.java:14) Truncated. see log file for complete stacktrace
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
使用 Docker 部署 Spring Boot 项目
Docker 技术发展为微服务落地提供了更加便利的环境,使用 Docker 部署 Spring Boot 其实非常简单,这篇文章我们就来简单学习下。首先构建一个简单的 S...
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
遥想当年,机缘巧合入了 ACM 的坑,周边巨擘林立,从此过上了"天天被虐似死狗"的生活… 然而我是谁,我可是死狗中的战斗鸡,智力不够那刷题来凑,开始了夜以继日哼哧哼哧刷题的日子,从此"读题与提交齐飞, AC 与 WA 一色 ",我惊喜的发现被题虐既刺激又有快感,那一刻我泪流满面。这么好的事儿作为一个正直的人绝不能自己独享,经过激烈的颅内斗争,我决定把我私藏的十几个 T 的,阿不,十几个刷题网...
白话阿里巴巴Java开发手册高级篇
不久前,阿里巴巴发布了《阿里巴巴Java开发手册》,总结了阿里巴巴内部实际项目开发过程中开发人员应该遵守的研发流程规范,这些流程规范在一定程度上能够保证最终的项目交付质量,通过在时间中总结模式,并推广给广大开发人员,来避免研发人员在实践中容易犯的错误,确保最终在大规模协作的项目中达成既定目标。 无独有偶,笔者去年在公司里负责升级和制定研发流程、设计模板、设计标准、代码标准等规范,并在实际工作中进行...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
redis分布式锁,面试官请随便问,我都会
文章有点长并且绕,先来个图片缓冲下! 前言 现在的业务场景越来越复杂,使用的架构也就越来越复杂,分布式、高并发已经是业务要求的常态。像腾讯系的不少服务,还有CDN优化、异地多备份等处理。 说到分布式,就必然涉及到分布式锁的概念,如何保证不同机器不同线程的分布式锁同步呢? 实现要点 互斥性,同一时刻,智能有一个客户端持有锁。 防止死锁发生,如果持有锁的客户端崩溃没有主动释放锁,也要保证锁可以正常释...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Java世界最常用的工具类库
Apache Commons Apache Commons有很多子项目 Google Guava 参考博客
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员...
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC...
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下...
为什么要学数据结构?
一、前言 在可视化化程序设计的今天,借助于集成开发环境可以很快地生成程序,程序设计不再是计算机专业人员的专利。很多人认为,只要掌握几种开发工具就可以成为编程高手,其实,这是一种误解。要想成为一个专业的开发人员,至少需要以下三个条件: 1) 能够熟练地选择和设计各种数据结构和算法 2) 至少要能够熟练地掌握一门程序设计语言 3) 熟知所涉及的相关应用领域的知识 其中,后两个条件比较容易实现,而第一个...
Android 9.0 init 启动流程
阅读五分钟,每日十点,和您一起终身学习,这里是程序员Android本篇文章主要介绍Android开发中的部分知识点,通过阅读本篇文章,您将收获以下内容:一、启动流程概述一、 启动流程概述Android启动流程跟Linux启动类似,大致分为如下五个阶段。1.开机上电,加载固化的ROM。2.加载BootLoader,拉起Android OS。3.加载Uboot,初始外设,引导Kernel启动等。...
相关热词 c# plc s1200 c#里氏转换原则 c# 主界面 c# do loop c#存为组套 模板 c# 停掉协程 c# rgb 读取图片 c# 图片颜色调整 最快 c#多张图片上传 c#密封类与密封方法
立即提问