1. 程式人生 > >MyBatis學習筆記(三)mybatis-config.xml都有哪些配置之typeAliases與plugins

MyBatis學習筆記(三)mybatis-config.xml都有哪些配置之typeAliases與plugins

類型別名(typeAlicases)

在mybatis-config.xml配置檔案中加入類描述

  <typeAliases>
        <typeAlias type="org.mybatis.example.User" alias="User" />
    </typeAliases>

或者新增要掃描的包名

    <typeAliases>
       <package name="org.mybatis.example" />
        <!--<typeAlias type="org.mybatis.example.User" alias="User" />-->
    </typeAliases>

 並在實體類添加註解@Alias

package org.mybatis.example;

import org.apache.ibatis.type.Alias;

@Alias("User")
public class User {

    public User(String userName) {
        this.userName = userName;
    }

    public User() {
    }

    private String userName;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}

然後在對映檔案xml中就可以用別名了

<select id="findAll"   resultType="User" parameterType="String">
        SELECT  `userName` FROM `jc_user` LIMIT 1
    </select>

外掛(plugins)

在mybatis-config.xml配置檔案中加入外掛類的配置

    <plugins>
        <plugin interceptor="org.mybatis.example.ExamplePlugin">
        </plugin>
    </plugins>

只需實現 Interceptor 介面,並指定想要攔截的方法簽名即可,目前專案中遇到的是拿這個外掛功能做了查詢分頁

package org.mybatis.example;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;

import java.util.Properties;

@Intercepts({@Signature(
        type= Executor.class,
        method = "query",
        args = {MappedStatement.class,Object.class})})
public class ExamplePlugin implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}