当前位置:首页 > WEB开发 > Web前端

抽丝剥茧JavaWeb当用之简单扯扯mybatis,Interceptor ,Filter

优良自学吧提供抽丝剥茧JavaWeb当用之简单扯扯mybatis,Interceptor ,Filter,抽丝剥茧JavaWeb应用之简单扯扯mybatis,Interceptor ,Filter 本文主要概述在项目中使用mybatis及springMVC的小知识点 1.使用my

抽丝剥茧JavaWeb应用之简单扯扯mybatis,Interceptor ,Filter

本文主要概述在项目中使用mybatis及springMVC的小知识点

1.使用mybatis往oracle插入数据,mybatis返回的依然是更新数据的条数,并将主键写入对象中,及mybatis批量插入数据。下面的两种情况均可使用在插入后,将userId写入到对象中。

<insert id="addUser" parameterType="com.model.UserVO">
		<selectKey keyProperty="userId" resultType="java.lang.String" 
			order="BEFORE">
				select SEQ_USER_SEQUENCE.NEXTVAL from dual
		</selectKey>
		insert into t_user (userId ,userName) values(userId,#{userName,jdbcType=VARCHAR})
</insert>


<insert id="addUser" parameterType="com.model.UserVO">
<selectKey keyProperty="userId" resultType="java.lang.String" 
			order="AFTER">
				select SEQ_USER_SEQUENCE.currval from dual
		</selectKey>
		insert into t_user (userId ,userName) values(SEQ_USER_SEQUENCE.NEXTVAL,#{userName, jdbcType=VARCHAR})
</insert>

2:大量数据插入:

addUsers(List<UserVO> lists)  //method
<insert id="addUsers" parameterType="java.util.List">
		insert into t_user (userId, userName)
		<foreach close=")" collection="list" item="item" index="index"
			open="(" separator="union">
			select
			#{item.userId,jdbcType=VARCHAR},
			#{item.userName,jdbcType=VARCHAR}
			from dual
		</foreach>
</insert>

	<insert id="demoinsert" parameterType="java.util.List">
		<foreach collection="list" item="item" index ="index" open="begin" close=";end;" separator=";">
			insert into t_role_resources  
			( role_id , resource_id , available , modify_date , modify_user) 
			values(#{item.roleId,jdbcType=VARCHAR} ,
#{item.resourceId ,jdbcType=INTEGER},#{item.available,jdbcType=VARCHAR},
			sysdate,#{item.modifyUser,jdbcType=VARCHAR} )
		</foreach>
	</insert>

此方法不适合特大数据的批量插入之后,一次性提交。大批量数据适合分批次提交,可参考博客:

http://blog.csdn.net/wlwlwlwl015/article/details/50246717

3:在操作数据库时,在开发环境下会测试每个sql的性能和耗时,可采用实现mybatis中的Interceptor

import java.util.Properties;
import java.lang.reflect.Method;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Intercepts(value = { 
        @Signature (type=Executor.class,
                method="update",
                args={MappedStatement.class,Object.class}),
        @Signature(type=Executor.class,
        method="query",
        args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class,
                CacheKey.class,BoundSql.class}),
        @Signature(type=Executor.class,
        method="query",
        args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})})
public class TimerInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(TimerInterceptor.class);
    
    /**
     * 实现拦截的地方
     * */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = invocation.getTarget();
        Object result = null;
        if (target instanceof Executor) {
            long start = System.currentTimeMillis();
            Method method = invocation.getMethod();
            /**执行方法*/
            result = invocation.proceed();
            long end = System.currentTimeMillis();
            logger.info("[TimerInterceptor] execute [" + method.getName() + "] cost [" + (end - start) + "] ms");
        }
        return result;
    }

    /**
     * Plugin.wrap生成拦截代理对象
     * */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}

然后在mybatis的配置文件中,将这个类配置成plugin 。

4.在前后端开发时,开发环境出现的跨域问题,可以写一个Filter,实现这个接口,这样在开发环境便于与其他人员调试code。

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
//		指定允许其他域名访问
		response.setHeader("Access-Control-Allow-Origin", "*");
//		表明它允许POST,GET,PUT,DELETE的外域请求
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//		不需要再发送预检验请求,可以缓存该结果
		response.setHeader("Access-Control-Max-Age", "3600");
//		表明它允许跨域请求包含content-type头
		response.setHeader("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");
		chain.doFilter(req, res);
	}

然后在应用的web.xml中配置这个Filter即可。

以上。不定期更新详扯。


(本文来自互联网,不代表搜站(http://www.ylzx8.cn/)的观点和立场)
本站所有内容来自互联网,若本站收录的信息无意侵犯了贵司版权,请给我们来信(ylzx8cn@163.com),我们会及时处理和回复,谢谢