MyBatis代码生成器以及拦截器

  • 代码生成器
  • 拦截器(分页插件)

一.代码生成器

maven 导包

<dependencies>
    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.46version>
    dependency>

    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.2.1version>
    dependency>
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-apiartifactId>
        <version>1.6.1version>
    dependency>
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-log4j12artifactId>
        <version>1.6.1version>
        <scope>runtimescope>
    dependency>
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.14version>
    dependency>

    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.12version>
        
    dependency>
dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.pluginsgroupId>
            <artifactId>maven-compiler-pluginartifactId>
            <configuration>
                <source>1.8source>
                <target>1.8target>
            configuration>
        plugin>
    plugins>
build>

1.2 准备代码生成器插件

POM.xml

 <build>
    <plugins>
        
        <plugin>
            <groupId>org.mybatis.generatorgroupId>
            <artifactId>mybatis-generator-maven-pluginartifactId>
            <version>1.3.2version>
            <configuration>
                
                
                <verbose>trueverbose>
                <overwrite>trueoverwrite>
            configuration>
        plugin>
    plugins>
build>

1.3 generatorConfig.xml

默认在资源夹根目录,必需叫这个名称




<generatorConfiguration>
    
    <classPathEntry   location="G:\openSource\mysql-connector-java-5.1.26-bin.jar"/>
    
    <context id="DB2Tables"   targetRuntime="MyBatis3Simple" >
        
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        commentGenerator>
        
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql:///mybatis"
                        userId="root" password="admin">
        jdbcConnection>
        
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>

        
        <javaModelGenerator targetPackage="wltyx.nyybw._02_generator.domain" targetProject="src/main/java">
            <property name="trimStrings" value="true"/>
        javaModelGenerator>
        
        <sqlMapGenerator targetPackage="wltyx.nyybw._02_generator.mapper" targetProject="src/main/resources">
        sqlMapGenerator>

        
        <javaClientGenerator type="XMLMAPPER" targetPackage="wltyx.nyybw._02_generator.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        javaClientGenerator>
        
        <table tableName="employee" domainObjectName="Employee">
            <generatedKey column="id" sqlStatement="MySql" />
        table>

       
    context>
generatorConfiguration>

二.MyBatis拦截器

  • 只需要知道语法就可以了
  • 用于增强功能

2.1 实现接口

2.1.1 拦截器中的方法

  • intercept:拦截的核心方法(在这里面实现相应的功能)
  • plugin:必需 return Plugin.wrap(o, this); 代表对于签名(在类上面的注解中)的拦截
  • setProperties:获取拦截器配置的参数

2.1.2 签名

  • type:对应的类(Executor.class,ResultSetHandler.class,ParameterHandler.class,StatementHandler.class)
    但是一般只用 Executor.class

  • method:type类中的方法名,我们一般只用 Executor.class中的update(增删改)与query(查询)

  • args:参数(方法中的参数类型)

//我要拦截增删改的功能
@Intercepts(
        //签名
      @Signature(
              type= Executor.class,
              method = "query",
              args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
      )
)
public class HelloInterceptor implements Interceptor {

    /**
     * 拦截器的核心方法(要做的事情是在这里完成的)
     * @param invocation
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("方法:"+invocation.getMethod());
        System.out.println("对象:"+invocation.getTarget());
        System.out.println("参数:"+invocation.getArgs());
        //执行相应的方法
        Object result = invocation.proceed();

        return result;
    }

    /**
     * 对哪些【签名】进行拦截(放行)
     *  哪些操作(修改与查询)会经过咱们的拦截方法:intercept
     * @param o
     * @return
     */
    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
       // return o;
    }

    /*
    
        
    
    */
    //接收参数
    @Override
    public void setProperties(Properties properties) {
        String dbType = properties.getProperty("dbType");
        System.out.println(dbType);
    }
}

2.2 拦截器的配置

  • 在mybatis-config.xml中进行配置

<plugins>
    <plugin interceptor="wltyx.nyybw._02_generator.interceptor.HelloInterceptor">
        <property name="dbType" value="mySql" />
    plugin>
plugins>

2.3 分页插件

分页插件就是一个拦截器

2.3.1 引入这个插件

 
<dependency>
    <groupId>com.github.pagehelpergroupId>
    <artifactId>pagehelperartifactId>
    <version>5.0.0version>
dependency>

2.3.3 插件配置

  • 在mybatis-config.xml中进行配置
<plugins>
    
    <plugin interceptor="com.github.pagehelper.PageInterceptor" />
plugins>
  • 集成spring的配置
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  
  <property name="plugins">
    <array>
      <bean class="com.github.pagehelper.PageInterceptor">bean>
    array>
  property>
bean>

2.3.3 使用分页插件

  • PageHelper.startPage(1, 10);
@Test
public void testPage() throws Exception{
    //分页 pageNum:第几页  pageSize:每页条数
    PageHelper.startPage(1, 10);

    SqlSession session = MyBatisUtil.openSession();
    EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
    List<Employee> employees = mapper.selectAll();
    Page page = (Page) employees;
    System.out.println("第几页:"+page.getPageNum()); //第几页
    System.out.println("总页数:"+page.getPages()); //总页数
    System.out.println("总条数:"+page.getTotal()); //总页数
    System.out.println("结果:"+page.getResult());

    page.getResult().forEach(e -> System.out.println(e));
}

三.SSM集成

SpringMVC,Spring,MyBatis

3.1 Spring与MyBatis集成

  • db.properites
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=admin
  • applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
  
    <context:component-scan base-package="wltyx.nyybw.ssm.service" />

  
  <context:property-placeholder location="classpath:db.properties" />

  
  <bean id="dataSource" class="org.apache.commons.dbcp.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>

  
  <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      
      <property name="dataSource" ref="dataSource" />
      
      <property name="typeAliasesPackage" value="wltyx.nyybw.ssm.domain" />
      
      <property name="mapperLocations" value="classpath:cn/itsource/ssm/mapper/*.xml" />
  bean>

  
   

  
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      
      <property name="basePackage" value="wltyx.nyybw.ssm.mapper" />
      <property name="sqlSessionFactoryBeanName" value="sessionFactory" />
  bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>

    
    <tx:annotation-driven transaction-manager="transactionManager" />

beans>

3.2 Spring与SpringMVC

  • applicationContext-mvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    
    <context:component-scan base-package="wltyx.nyybw.ssm.controller" />
    
    <mvc:default-servlet-handler />
    
    <mvc:annotation-driven />
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    bean>

    
    
beans>
  • web.xml

<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>


<servlet>
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <load-on-startup>1load-on-startup>
    <init-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext-mvc.xmlparam-value>
    init-param>
servlet>
<servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
servlet-mapping>
  • 注意:不要在mvc的配置文件中去引入spring的核心配置文件(有些框【shiro】架就无法使用)

你可能感兴趣的:(Mybatis,后台框架)