DAO
1 package com.cmbc.dao; 2 3 import com.cmbc.po.Shopcart; 4 import org.springframework.stereotype.Repository; 5 6 import java.util.List; 7 8 @Repository("shopcartDao") 9 public interface ShopcartMapper { 10 int deleteByPrimaryKey(Integer shopcardId); 11 12 int insert(Shopcart record); 13 14 int insertSelective(Shopcart record); 15 16 Shopcart selectByPrimaryKey(Integer shopcardId); 17 18 int updateByPrimaryKeySelective(Shopcart record); 19 20 int updateByPrimaryKey(Shopcart record); 21 22 List<Shopcart> getShopcartsByUserId(int userId); 23 }
mapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > 3 <mapper namespace="com.cmbc.dao.ShopcartMapper" > 4 <resultMap id="BaseResultMap" type="com.cmbc.po.Shopcart" > 5 <id column="shopcard_id" property="shopcardId" jdbcType="INTEGER" /> 6 <result column="food_id" property="foodId" jdbcType="INTEGER" /> 7 <result column="shopcard_count" property="shopcardCount" jdbcType="INTEGER" /> 8 <result column="shopcard_sum" property="shopcardSum" jdbcType="DOUBLE" /> 9 <result column="user_id" property="userId" jdbcType="INTEGER" /> 10 </resultMap> 11 <sql id="Base_Column_List" > 12 shopcard_id, food_id, shopcard_count, shopcard_sum, user_id 13 </sql> 14 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > 15 select 16 <include refid="Base_Column_List" /> 17 from shopcart 18 where shopcard_id = #{shopcardId,jdbcType=INTEGER} 19 </select> 20 21 <select id="getShopcartsByUserId" resultMap="BaseResultMap" parameterType="java.lang.Integer" > 22 select 23 <include refid="Base_Column_List" /> 24 from shopcart 25 where user_id = #{userId,jdbcType=INTEGER} 26 </select> 27 28 29 30 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > 31 delete from shopcart 32 where shopcard_id = #{shopcardId,jdbcType=INTEGER} 33 </delete> 34 <insert id="insert" parameterType="com.cmbc.po.Shopcart" > 35 insert into shopcart (shopcard_id, food_id, shopcard_count, 36 shopcard_sum, user_id) 37 values (#{shopcardId,jdbcType=INTEGER}, #{foodId,jdbcType=INTEGER}, #{shopcardCount,jdbcType=INTEGER}, 38 #{shopcardSum,jdbcType=DOUBLE}, #{userId,jdbcType=INTEGER}) 39 </insert> 40 <insert id="insertSelective" parameterType="com.cmbc.po.Shopcart" > 41 insert into shopcart 42 <trim prefix="(" suffix=")" suffixOverrides="," > 43 <if test="shopcardId != null" > 44 shopcard_id, 45 </if> 46 <if test="foodId != null" > 47 food_id, 48 </if> 49 <if test="shopcardCount != null" > 50 shopcard_count, 51 </if> 52 <if test="shopcardSum != null" > 53 shopcard_sum, 54 </if> 55 <if test="userId != null" > 56 user_id, 57 </if> 58 </trim> 59 <trim prefix="values (" suffix=")" suffixOverrides="," > 60 <if test="shopcardId != null" > 61 #{shopcardId,jdbcType=INTEGER}, 62 </if> 63 <if test="foodId != null" > 64 #{foodId,jdbcType=INTEGER}, 65 </if> 66 <if test="shopcardCount != null" > 67 #{shopcardCount,jdbcType=INTEGER}, 68 </if> 69 <if test="shopcardSum != null" > 70 #{shopcardSum,jdbcType=DOUBLE}, 71 </if> 72 <if test="userId != null" > 73 #{userId,jdbcType=INTEGER}, 74 </if> 75 </trim> 76 </insert> 77 <update id="updateByPrimaryKeySelective" parameterType="com.cmbc.po.Shopcart" > 78 update shopcart 79 <set > 80 <if test="foodId != null" > 81 food_id = #{foodId,jdbcType=INTEGER}, 82 </if> 83 <if test="shopcardCount != null" > 84 shopcard_count = #{shopcardCount,jdbcType=INTEGER}, 85 </if> 86 <if test="shopcardSum != null" > 87 shopcard_sum = #{shopcardSum,jdbcType=DOUBLE}, 88 </if> 89 <if test="userId != null" > 90 user_id = #{userId,jdbcType=INTEGER}, 91 </if> 92 </set> 93 where shopcard_id = #{shopcardId,jdbcType=INTEGER} 94 </update> 95 <update id="updateByPrimaryKey" parameterType="com.cmbc.po.Shopcart" > 96 update shopcart 97 set food_id = #{foodId,jdbcType=INTEGER}, 98 shopcard_count = #{shopcardCount,jdbcType=INTEGER}, 99 shopcard_sum = #{shopcardSum,jdbcType=DOUBLE}, 100 user_id = #{userId,jdbcType=INTEGER} 101 where shopcard_id = #{shopcardId,jdbcType=INTEGER} 102 </update> 103 </mapper>
spring-mybatis.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xsi:schemaLocation=" 6 http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 8 http://www.springframework.org/schema/tx 9 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 12 "> 13 14 <!-- JNDI方式配置数据源 --> 15 <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> 16 <property name="jndiName" value="${jndiName}"></property> </bean> --> 17 18 <!-- 配置数据源 --> 19 <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" 20 init-method="init" destroy-method="close"> 21 <property name="url" value="${jdbc_url}" /> 22 <property name="username" value="${jdbc_username}" /> 23 <property name="password" value="${jdbc_password}" /> 24 25 <!-- 初始化连接大小 --> 26 <property name="initialSize" value="0" /> 27 <!-- 连接池最大使用连接数量 --> 28 <property name="maxActive" value="20" /> 29 <!-- 连接池最大空闲 --> 30 <property name="maxIdle" value="20" /> 31 <!-- 连接池最小空闲 --> 32 <property name="minIdle" value="0" /> 33 <!-- 获取连接最大等待时间 --> 34 <property name="maxWait" value="60000" /> 35 36 <!-- <property name="poolPreparedStatements" value="true" /> <property 37 name="maxPoolPreparedStatementPerConnectionSize" value="33" /> --> 38 39 <property name="validationQuery" value="${validationQuery}" /> 40 <property name="testOnBorrow" value="false" /> 41 <property name="testOnReturn" value="false" /> 42 <property name="testWhileIdle" value="true" /> 43 44 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> 45 <property name="timeBetweenEvictionRunsMillis" value="60000" /> 46 <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> 47 <property name="minEvictableIdleTimeMillis" value="25200000" /> 48 49 <!-- 打开removeAbandoned功能 --> 50 <property name="removeAbandoned" value="true" /> 51 <!-- 1800秒,也就是30分钟 --> 52 <property name="removeAbandonedTimeout" value="1800" /> 53 <!-- 关闭abanded连接时输出错误日志 --> 54 <property name="logAbandoned" value="true" /> 55 56 <!-- 监控数据库 --> 57 <!-- <property name="filters" value="stat" /> --> 58 <property name="filters" value="mergeStat" /> 59 </bean> 60 61 <!-- myBatis文件 --> 62 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 63 <property name="dataSource" ref="dataSource" /> 64 <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 --> 65 <property name="mapperLocations" value="classpath:com/cmbc/mapper/*.xml" /> 66 <!-- 加载mybatis分页插件 --> 67 <property name="plugins"> 68 <list> 69 <bean class="com.cmbc.paginator.OffsetLimitInterceptor"> 70 <property name="dialectClass" value="com.cmbc.dialect.MySQLDialect"></property> 71 </bean> 72 </list> 73 74 </property> 75 </bean> 76 77 <!-- sqlSession --> 78 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> 79 <constructor-arg index="0" ref="sqlSessionFactory" /> 80 </bean> 81 82 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 83 <property name="basePackage" value="com.cmbc.dao" /> 84 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> 85 </bean> 86 87 <!-- 配置事务管理器 --> 88 <bean id="transactionManager" 89 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 90 <property name="dataSource" ref="dataSource" /> 91 </bean> 92 93 <!-- 注解方式配置事物 --> 94 <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> 95 96 <!-- 拦截器方式配置事物 --> 97 <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> 98 <tx:attributes> 99 <tx:method name="add*" propagation="REQUIRED" /> 100 <tx:method name="append*" propagation="REQUIRED" /> 101 <tx:method name="insert*" propagation="REQUIRED" /> 102 <tx:method name="save*" propagation="REQUIRED" /> 103 <tx:method name="update*" propagation="REQUIRED" /> 104 <tx:method name="modify*" propagation="REQUIRED" /> 105 <tx:method name="edit*" propagation="REQUIRED" /> 106 <tx:method name="delete*" propagation="REQUIRED" /> 107 <tx:method name="remove*" propagation="REQUIRED" /> 108 <tx:method name="repair" propagation="REQUIRED" /> 109 <tx:method name="delAndRepair" propagation="REQUIRED" /> 110 111 <tx:method name="get*" propagation="SUPPORTS" /> 112 <tx:method name="find*" propagation="SUPPORTS" /> 113 <tx:method name="load*" propagation="SUPPORTS" /> 114 <tx:method name="search*" propagation="SUPPORTS" /> 115 <tx:method name="datagrid*" propagation="SUPPORTS" /> 116 117 <tx:method name="*" propagation="SUPPORTS" /> 118 </tx:attributes> 119 </tx:advice> 120 <aop:config> 121 <aop:pointcut id="transactionPointcut" 122 expression="execution(* com.cmbc.service..*Impl.*(..))" /> 123 <aop:advisor pointcut-ref="transactionPointcut" 124 advice-ref="transactionAdvice" /> 125 </aop:config> 126 127 128 <!-- 配置druid监控spring jdbc --> 129 <bean id="druid-stat-interceptor" 130 class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> 131 </bean> 132 <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" 133 scope="prototype"> 134 <property name="patterns"> 135 <list> 136 <value>com.cmbc.service.*</value> 137 </list> 138 </property> 139 </bean> 140 <aop:config> 141 <aop:advisor advice-ref="druid-stat-interceptor" 142 pointcut-ref="druid-stat-pointcut" /> 143 </aop:config> 144 145 </beans>
测试类
1 package com.cmbc.test; 2 3 import com.alibaba.fastjson.JSON; 4 import com.cmbc.dao.ShopcartMapper; 5 import com.cmbc.po.Shopcart; 6 import org.junit.Test; 7 import org.junit.runner.RunWith; 8 import org.springframework.test.context.ContextConfiguration; 9 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 10 11 import javax.annotation.Resource; 12 import java.util.List; 13 14 /** 15 * Created by admin on 2016/6/25. 16 */ 17 @RunWith(SpringJUnit4ClassRunner.class) 18 @ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mybatis.xml"}) 19 public class TestShopcartMapper { 20 21 private ShopcartMapper shopcartMapper; 22 23 @Test 24 public void test1() { 25 26 Shopcart shopcart = shopcartMapper.selectByPrimaryKey(1); 27 System.out.println(JSON.toJSONString(shopcart)); 28 } 29 30 31 @Test 32 public void test2() { 33 List<Shopcart> shopcarts = shopcartMapper.getShopcartsByUserId(1); 34 System.out.println(JSON.toJSONString(shopcarts)); 35 } 36 37 @Resource(name = "shopcartDao") 38 public void setShopcartMapper(ShopcartMapper shopcartMapper) { 39 this.shopcartMapper = shopcartMapper; 40 } 41 }
报错
1 [DEBUG] 2016-06-26 10:08:27,167 method:org.springframework.test.context.web.ServletTestExecutionListener.afterTestMethod(ServletTestExecutionListener.java:96) 2 Resetting RequestContextHolder for test context [TestContext@4958b2cc testClass = TestShopcartMapper, testInstance = com.cmbc.test.TestShopcartMapper@5e4294b2, testMethod = test2@TestShopcartMapper, testException = java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.cmbc.dao.ShopcartMapper.getShopcartsByUserId, mergedContextConfiguration = [MergedContextConfiguration@1632dfd4 testClass = TestShopcartMapper, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]. 3 4 java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for com.cmbc.dao.ShopcartMapper.getShopcartsByUserId 5 6 at org.apache.ibatis.session.Configuration$StrictMap.get(Configuration.java:672) 7 at org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:507) 8 at org.apache.ibatis.session.Configuration.getMappedStatement(Configuration.java:500) 9 at org.apache.ibatis.binding.MapperMethod.setupCommandType(MapperMethod.java:240) 10 at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:71) 11 at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:39) 12 at com.sun.proxy.$Proxy15.getShopcartsByUserId(Unknown Source) 13 at com.cmbc.test.TestShopcartMapper.test2(TestShopcartMapper.java:32) 14 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 15 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 16 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 17 at java.lang.reflect.Method.invoke(Method.java:606) 18 at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) 19 at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 20 at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) 21 at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 22 at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) 23 at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) 24 at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) 25 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) 26 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) 27 at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) 28 at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) 29 at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) 30 at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) 31 at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) 32 at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 33 at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) 34 at org.junit.runners.ParentRunner.run(ParentRunner.java:309) 35 at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) 36 at org.junit.runner.JUnitCore.run(JUnitCore.java:160) 37 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119) 38 at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42) 39 at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234) 40 at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74) 41 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 42 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 43 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 44 at java.lang.reflect.Method.invoke(Method.java:606) 45 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) 46 47 [DEBUG] 2016-06-26 10:08:27,180 method:org.springframework.test.context.support.DirtiesContextTestExecutionListener.afterTestClass(DirtiesContextTestExecutionListener.java:112) 48 After test class: context [[TestContext@4958b2cc testClass = TestShopcartMapper, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@1632dfd4 testClass = TestShopcartMapper, locations = '{classpath:spring.xml, classpath:spring-mybatis.xml}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader']]], dirtiesContext [false]. 49 [INFO ] 2016-06-26 10:08:27,183 method:org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1042) 50 Closing org.springframework.context.support.GenericApplicationContext@7305830a: startup date [Sun Jun 26 10:08:23 CST 2016]; root of context hierarchy 51 [DEBUG] 2016-06-26 10:08:27,184 method:org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:246) 52 Returning cached instance of singleton bean 'sqlSessionFactory' 53 [DEBUG] 2016-06-26 10:08:27,185 method:org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:246) 54 Returning cached instance of singleton bean 'lifecycleProcessor' 55 [INFO ] 2016-06-26 10:08:27,186 method:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:444) 56 Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@28741848: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,shopcartService,userService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,dataSource,sqlSessionFactory,sqlSession,org.mybatis.spring.mapper.MapperScannerConfigurer#0,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.importAwareProcessor,foodMapper,informationMapper,menuMapper,merchantMapper,msgnoteMapper,orderMapper,shopcartDao,userDao]; root of factory hierarchy 57 [DEBUG] 2016-06-26 10:08:27,186 method:org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:219) 58 Invoking destroy() on bean with name 'druid-stat-interceptor' 59 [DEBUG] 2016-06-26 10:08:27,186 method:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:500) 60 Retrieved dependent beans for bean '(inner bean)': [transactionAdvice] 61 [DEBUG] 2016-06-26 10:08:27,187 method:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:500) 62 Retrieved dependent beans for bean 'shopcartDao': [com.cmbc.test.TestShopcartMapper] 63 [DEBUG] 2016-06-26 10:08:27,187 method:org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:500) 64 Retrieved dependent beans for bean 'com.cmbc.paginator.OffsetLimitInterceptor#4485af5c': [sqlSessionFactory] 65 [DEBUG] 2016-06-26 10:08:27,187 method:org.springframework.beans.factory.support.DisposableBeanAdapter.invokeCustomDestroyMethod(DisposableBeanAdapter.java:295) 66 Invoking destroy method 'close' on bean with name 'dataSource' 67 [INFO ] 2016-06-26 10:08:27,192 method:com.alibaba.druid.pool.DruidDataSource.close(DruidDataSource.java:982) 68 {dataSource-1} closed 69 70 Process finished with exit code -1