springMvc+mybatis配置

web.xml:

 

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <display-name>测试</display-name>

  <distributable/>

  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
    <!--异步请求方式-->
    <async-supported>true</async-supported>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>SpringMVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:/spring-test.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>

  <servlet-mapping>
    <servlet-name>SpringMVC Dispatcher Servlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>


spring-test.xml:

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--引入mybatis配置-->
    <import resource="classpath:applicationContext.xml"/>
    <!--引入拦截器-->
    <import resource="spring-authorization.xml"/>
    <!--rest服务返回对象,支持xml与json格式,默认返回json-->
    <mvc:annotation-driven>
        <mvc:async-support default-timeout="30000"/>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper" ref="objectMapper"></property>
            </bean>
            <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter">
                <property name="objectMapper" ref="xmlMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
          p:indentOutput="true"
          p:simpleDateFormat="yyyy-MM-dd"
          p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule">
    </bean>
    <bean id="xmlMapper" parent="objectMapper" p:createXmlMapper="true"/>

</beans>

 

 

applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
		                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		                    http://www.springframework.org/schema/context 
		                    http://www.springframework.org/schema/context/spring-context-3.0.xsd
		                    http://www.springframework.org/schema/tx 
		                    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		                    http://www.springframework.org/schema/aop 
		                    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">


	<!-- 配置外部数据库连接信息-->
	<context:property-placeholder location="classpath:db.properties"/>

	<!--扫描制定包下所有的注解-->
	<context:component-scan base-package="test"/>

	<!--向容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor 以及 RequiredAnnotationBeanPostProcessor 这 4 个BeanPostProcessor,
component-scan 包含该功能 因此可以删除-->
	<!--<context:annotation-config/>-->

	<!--当<aop:aspectj-autoproxy/>时,spring会自动在JDK动态代理和CGLIB之间转换
        当为<aop:aspectj-autoproxy proxy-target-class="true"/>时,spring使用cglib的代理方式
        当为<aop:aspectj-autoproxy proxy-target-class="false"/>时,spring使用JDK的代理方式
        JDK动态代理只能对实现了接口的类生成代理,而不能针对类
        CGLIB是针对类实现代理,主要是对指定的类生成一个子类,覆盖其中的方法
        因为是继承,所以该类或方法最好不要声明成final
    -->
	<aop:aspectj-autoproxy/>

	<!-- 配置第数据源 -->
	<bean id="dataSourceTest" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="${jdbc.driverClassName}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
	</bean>
	<!--数据的mybatis配置-->
	<bean id="sqlSessionFactoryTest" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSourceTest" />
		<!--mybatis.xml配置路径-->
		<property name="mapperLocations" value="classpath*:mybatis/mapper/*/**/*.xml"/>
		<!--基础配置-->
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
	</bean>
	<!-- 数据源的配置事务管理器 -->
	<bean id="transactionManagerTest" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSourceTest" />
		<property name="nestedTransactionAllowed" value="true"/>
	</bean>
	<tx:advice id="txAdviceTest" transaction-manager="transactionManagerTest">
		<tx:attributes>
			<!--只读,制定异常为UnexpectedRollbackException-->
			<tx:method name="get*" read-only="true" rollback-for="UnexpectedRollbackException"/>
			<!--REQUIRED如果上下文中已经存在事务,则加入;否则,开启一个事务。-->
			<tx:method name="*_tx" rollback-for="Exception" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<!--为test下所有包的方法添加事物-->
		<aop:pointcut id="txPointCutTest" expression="execution(* test..*.*(..))"/>
		<aop:advisor advice-ref="txAdviceTest" pointcut-ref="txPointCutTest"/>
	</aop:config>	
</beans>                    <!--mybatis.xml配置路径-->
		<property name="mapperLocations" value="classpath*:mybatis/mapper/*/**/*.xml"/>
		<!--基础配置-->
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
	</bean>
	<!-- 数据源的配置事务管理器 -->
	<bean id="transactionManagerTest" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSourceTest" />
		<property name="nestedTransactionAllowed" value="true"/>
	</bean>
	<tx:advice id="txAdviceTest" transaction-manager="transactionManagerTest">
		<tx:attributes>
			<!--只读,制定异常为UnexpectedRollbackException-->
			<tx:method name="get*" read-only="true" rollback-for="UnexpectedRollbackException"/>
			<!--REQUIRED如果上下文中已经存在事务,则加入;否则,开启一个事务。-->
			<tx:method name="*_tx" rollback-for="Exception" propagation="REQUIRED"/>
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<!--为test下所有包的方法添加事物-->
		<aop:pointcut id="txPointCutTest" expression="execution(* test..*.*(..))"/>
		<aop:advisor advice-ref="txAdviceTest" pointcut-ref="txPointCutTest"/>
	</aop:config>	
</beans>                    

 

mybatis-config.xml:
 
 
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 自增主见 --> <setting name="useGeneratedKeys" value="true"/> <!--开启二级缓存-->
 
 
 
 
 
 

<setting name="cacheEnabled" value="true"/> <!--已log4j形式输出日志--> <setting name="logImpl" value="LOG4J2"/> <!--<setting name="lazyLoadingEnabled" value="true"/> <setting name="aggressiveLazyLoading" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="autoMappingBehavior" value="FULL"/> <setting name="defaultExecutorType" value="BATCH"/> <setting name="defaultStatementTimeout" value="25000"/>--> </settings></configuration>

 
 

mybatis.xml了:

 
 
 
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="test.mapper.TestMapper" > <!--自定义二级缓存的实现 eviction="LRU" 移除时间相差最多的 eviction="FIFO" 先进先出 eviction="SOFT" 软引用 eviction="WEAK" 弱引用 --> <cache type="com.dqys.core.cache.MybatisRedisCache" eviction="LRU"/> <resultMap id="BaseResultMap" type="test.pojo.Test" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List" > id, name </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from test where id = #{id,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from test where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="test.pojo.Test" > insert into test (id, name) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="test.pojo.Test" > insert into test <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="name != null" > name, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=INTEGER}, </if> <if test="name != null" > #{name,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="test.pojo.Test" > update test <set > <if test="name != null" > name = #{name,jdbcType=VARCHAR}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="test.pojo.Test" > update test set name = #{name,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} </update> </mapper>

 

MybatisRedisCache(这个为样例,该类根据需求自己实现,其中key值为"命名空间+查询语句")

 

 
package com.dqys.core.cache; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.SerializationUtils; import org.apache.ibatis.cache.Cache; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.io.*; import java.util.Properties; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @author by yan on 2/18/16. */ public class MybatisRedisCache implements Cache { private static final int DB_INDEX = 1; private static final String UTF_8 = "utf-8"; private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final String COMMON_CACHE_KEY = "COM:"; private String id; private JedisPool jedisPool; private Properties properties; { properties = getProp(); JedisPoolConfig config = new JedisPoolConfig(); /*config.setMaxIdle(Integer.valueOf(properties .getProperty("redis.pool.maxIdle")));*/ jedisPool = new JedisPool(config, properties.getProperty("redis.cache.host"), Integer.valueOf(properties.getProperty("redis.cache.port")), 0, properties.getProperty("redis.cache.password")); } public MybatisRedisCache() { } public MybatisRedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("必须传入ID"); } this.id = id; } public String getId() { return this.id; } public void putObject(Object key, Object value) { Jedis jedis = null; boolean borrowOrOprSuccess = true; try { jedis = jedisPool.getResource(); jedis.select(DB_INDEX); byte[] keys = getKey(key).getBytes(UTF_8); jedis.set(keys, SerializationUtils.serialize((Serializable) value)); } catch (Exception e) { borrowOrOprSuccess = false; if (jedis != null) jedisPool.returnBrokenResource(jedis); } finally { if (borrowOrOprSuccess) jedisPool.returnResource(jedis); } } public Object getObject(Object key) { Jedis jedis = null; Object value = null; boolean borrowOrOprSuccess = true; try { jedis = jedisPool.getResource(); jedis.select(DB_INDEX); value = SerializationUtils.deserialize(jedis.get(getKey(key).getBytes(UTF_8))); } catch (Exception e) { borrowOrOprSuccess = false; if (jedis != null) jedisPool.returnBrokenResource(jedis); } finally { if (borrowOrOprSuccess) jedisPool.returnResource(jedis); } return value; } public Object removeObject(Object key) { Jedis jedis = null; Object value = null; boolean borrowOrOprSuccess = true; try { jedis = jedisPool.getResource(); jedis.select(DB_INDEX); value = jedis.del(getKey(key).getBytes(UTF_8)); } catch (Exception e) { borrowOrOprSuccess = false; if (jedis != null) jedisPool.returnBrokenResource(jedis); } finally { if (borrowOrOprSuccess) jedisPool.returnResource(jedis); } return value; } public void clear() { Jedis jedis = null; boolean borrowOrOprSuccess = true; try { jedis = jedisPool.getResource(); jedis.select(DB_INDEX); Set<byte[]> keys = jedis.keys(getKeys().getBytes(UTF_8)); for (byte[] key : keys) { jedis.del(key); } } catch (Exception e) { borrowOrOprSuccess = false; if (jedis != null) jedisPool.returnBrokenResource(jedis); } finally { if (borrowOrOprSuccess) jedisPool.returnResource(jedis); } } public int getSize() { Jedis jedis = null; int result = 0; boolean borrowOrOprSuccess = true; try { jedis = jedisPool.getResource(); jedis.select(DB_INDEX); Set<byte[]> keys = jedis.keys(getKeys().getBytes(UTF_8)); if (null != keys && !keys.isEmpty()) { result = keys.size(); } } catch (Exception e) { borrowOrOprSuccess = false; if (jedis != null) jedisPool.returnBrokenResource(jedis); } finally { if (borrowOrOprSuccess) jedisPool.returnResource(jedis); } return result; } public ReadWriteLock getReadWriteLock() { return readWriteLock; } /** * 按照一定规则标识key */ private String getKey(Object key) { StringBuilder accum = new StringBuilder(); accum.append(COMMON_CACHE_KEY); accum.append(this.id).append(":"); accum.append(DigestUtils.md5Hex(String.valueOf(key))); return accum.toString(); } /** * redis key规则前缀 */ private String getKeys() { return COMMON_CACHE_KEY + this.id + ":*"; } /** * 加载项目redis连接属性文件 */ private Properties getProp() { if (properties == null || properties.isEmpty()) { properties = new Properties(); InputStream is = null; BufferedReader bf = null; try { is = this.getClass().getResourceAsStream("/config.properties");//将地址加在到文件输入流中 bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));//转为字符流,设置编码为UTF-8防止出现乱码 properties.load(bf); } catch (UnsupportedEncodingException e) { } catch (FileNotFoundException e) { } catch (IOException e) { } catch (Exception e) { } finally { try {//文件流关闭 if (bf != null) { bf.close(); } if (is != null) { is.close(); } } catch (IOException e) { } } } return properties; } } 
 

java代码:

 
 
TestMapper:
 
package test.mapper; import test.pojo.Test; public interface TestMapper { int deleteByPrimaryKey(Integer id); int insert(Test record); int insertSelective(Test record); Test selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(Test record); int updateByPrimaryKey(Test record); }
TestMapperImpl:
 
package test.mapper.impl; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Repository; import test.base.TestSaleBaseDao; import test.mapper.TestMapper; import test.pojo.Test; /** * Created by yan on 17-3-27. */ @Repository//标注数据访问组件 @Primary//单列 public class TestMapperImpl extends TestSaleBaseDao implements TestMapper { public int deleteByPrimaryKey(Integer id) { return 0; } public int insert(Test record) { return 0; } public int insertSelective(Test record) { return 0; } public Test selectByPrimaryKey(Integer id) { return super.getSqlSession().getMapper(TestMapper.class).selectByPrimaryKey(id); } public int updateByPrimaryKeySelective(Test record) { return 0; } public int updateByPrimaryKey(Test record) { return 0; } } 
 
TestService:
 
package test; import org.springframework.stereotype.Service; import test.pojo.Test; /** * Created by yan on 17-3-27. */ @Service public interface TestService { Test selectByPrimaryKey(Integer id); }

 

TestServiceImpl:

 

 
 
package test.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Repository; import test.TestService; import test.mapper.TestMapper; import test.pojo.Test; /** * Created by yan on 17-3-27. */ @Repository @Primary public class TestServiceImpl implements TestService { @Autowired private TestMapper testMapper; public Test selectByPrimaryKey(Integer id) { return testMapper.selectByPrimaryKey(id); } } 

 

 

 

 

 

 

 

 
 

 

TestController:

 

 
package test.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import test.TestService; import test.pojo.Test; /** * Created by yan on 17-3-27. */ @RestController @RequestMapping(value = "/test") public class TestController { @Autowired private TestService testService; @RequestMapping(value = "/{id}",method = RequestMethod.GET, produces = "application/json") public Test get(@PathVariable("id") Integer id){ return testService.selectByPrimaryKey(id); } }

 

 

 

 

 

 
 
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值