Simple to pull mybatis, Interceptor, Filter for Java Web application

This article mainly outlines the small knowledge points of using mybatis and springMVC in the project

1. Use mybatis to insert data into oracle, mybatis still returns the number of updated data, and writes the primary key into the object, and mybatis inserts data in batches. The following two cases can be used to write the userId to the object after insertion.

<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: Mass data insertion:

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>

  This method is not suitable for one-time submission after batch insertion of very large data. Large batches of data are suitable for batch submission, please refer to the blog:

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

 

3: When operating the database, the performance and time-consuming of each sql will be tested in the development environment, and the Interceptor in mybatis can be implemented

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);
    
    /**
     * Where to implement interception
     * */
    @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();
            /**Execute method*/
            result = invocation.proceed();
            long end = System.currentTimeMillis();
            logger.info("[TimerInterceptor] execute [" + method.getName() + "] cost [" + (end - start) + "] ms");
        }
        return result;
    }

    /**
     * Plugin.wrap generates interception proxy object
     * */
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

}

 Then in the configuration file of mybatis, configure this class as a plugin.

4. In front-end and back-end development, if there are cross-domain problems in the development environment, you can write a Filter to implement this interface, so that it is convenient to debug the code with other personnel in the development environment.

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletResponse response = (HttpServletResponse) res;
// Specify to allow other domain names to access
		response.setHeader("Access-Control-Allow-Origin", "*");
// Indicates that it allows POST, GET, PUT, DELETE external domain requests
		response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
// No need to send a pre-check request, the result can be cached
		response.setHeader("Access-Control-Max-Age", "3600");
// Indicates that it allows cross-origin requests to include content-type headers
		response.setHeader("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");
		chain.doFilter(req, res);
	}

Then configure this Filter in the web.xml of the application. 

above. Update details from time to time.

 

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326572079&siteId=291194637