折腾-wordpress+grpc+java对接(5)java整合mybatis,代码自动生成和分页

spring boot 整合Mybatis 有两种常用的方式,注解和xml,两种方式各有优劣,所以本篇将集成这两种方式,为了减少工作量也集成代码生成和分页。接上面java程序,主要改动是wp-grpc-server项目

1. 配置

  1. pom.xml配置
    <?xml version="1.0"?>
    <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    
    <artifactId>wp-grpc-server</artifactId>
    <name>wp-grpc-server</name>
    <packaging>jar</packaging>
    
    <parent>
        <groupId>com.datayang</groupId>
        <artifactId>java-grpc-wp</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    
    <dependencies>
            <!-- spring boot web -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.1</version>
            </dependency>
    
    
            <!-- mysql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
    
            <!-- 通用mapper -->
            <dependency>
                <groupId>tk.mybatis</groupId>
                <artifactId>mapper-spring-boot-starter</artifactId>
                <version>2.1.5</version>
            </dependency>
            <!-- pagehelper 分页插件 -->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>5.1.11</version>
            </dependency>
    
            <dependency>
                <groupId>com.datayang</groupId>
                <artifactId>wp-grpc-lib</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
            <!-- rpc service -->
            <dependency>
                <groupId>net.devh</groupId>
                <artifactId>grpc-server-spring-boot-starter</artifactId>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
    
                <!-- 自动生成代码 -->
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <!-- <version>1.3.5</version> -->
                    <version>1.3.7</version>
                    <dependencies>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>5.1.47</version>
                        </dependency>
                        <dependency>
                            <groupId>tk.mybatis</groupId>
                            <artifactId>mapper</artifactId>
                            <version>4.1.5</version>
                        </dependency>
                    </dependencies>
                    <executions>
                        <execution>
                            <id>Generate MyBatis Artifacts</id>
                            <phase>package</phase>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <!--允许移动生成的文件 -->
                        <verbose>true</verbose>
                        <!-- 是否覆盖 -->
                        <overwrite>true</overwrite>
                        <!-- 自动生成的配置 -->
                        <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    
    1. 配置application.yml,里面包含,分页和debug模式打开
      spring:
      application:
          name: local-grpc-server
      datasource:
          url: jdbc:mysql://localhost:3306/wordpress?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
      
      mybatis:
      # 驼峰命名规范 如:数据库字段是  order_id 那么 实体字段就要写成 orderId
      configuration:
          map-underscore-to-camel-case: true
      # type-aliases扫描路径
      type-aliases-package: com.datayang.wp.bean
      # mapper xml实现扫描路径
      mapper-locations: classpath:mapper/*.xml
      property:
          order: BEFORE
      
      #pagehelper分页配置 第二种和第三种不需要 重点讲的第一种需要
      pagehelper:
      helperDialect: mysql
      reasonable: true
      supportMethodsArguments: true
      params: count=countSql
      
      logging:
      level:
          com:
          datayang:
              wp:
              dao: debug
      grpc:
      server:
          port: 9898
      
      server:
      port: 8333
      
    2. 代码自动生成mybatis-generator.xml配置
      
      <!DOCTYPE generatorConfiguration
              PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
              "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
      <generatorConfiguration>
          <!-- defaultModelType="flats" 设置复合主键时不单独为主键创建实体  targetRuntime="MyBatis3"MyBatis3Simple将不会生成sample动态代码-->
          <context id="mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
              <property name="javaFileEncoding" value="UTF-8"/>
              <!-- 当表名或者字段名为SQL关键字的时候,可以设置该属性为true,MBG会自动给表名或字段名添加分隔符(反单引号) -->
              <property name="autoDelimitKeywords" value="true"/>
              <!-- 由于beginningDelimiter和endingDelimiter的默认值为双引号("),在Mysql中不能这么写,所以还要将这两个默认值改为反单引号(`), -->
              <property name="beginningDelimiter" value="`"/>
              <property name="endingDelimiter" value="`"/> 
      
              <!-- 生成的POJO实现java.io.Serializable接口 -->
              <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
      
              <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
                  <property name="mappers" value="com.datayang.wp.config.MyMapper"/>
                  <!--caseSensitive默认false,当数据库表名区分大小写时,可以将该属性设置为true-->
                  <property name="caseSensitive" value="false"/>
              </plugin>
      
              <!--注释-->
              <commentGenerator>
                  <property name="javaFileEncoding" value="UTF-8"/>
                  <!-- 阻止生成注释 -->
                  <property name="suppressAllComments" value="true"/>
                  <!-- 注释里不添加日期 -->
                  <property name="suppressDate" value="true"/>
              </commentGenerator>
      
              <!--数据库链接地址账号密码-->
              <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/wordpress?useSSL=false"
                              userId="root" password="123456">
              </jdbcConnection>
              <javaTypeResolver>
                  <property name="forceBigDecimals" value="false"/>
              </javaTypeResolver>
      
              <!--生成Model类存放位置-->
              <javaModelGenerator targetPackage="com.datayang.wp.bean" targetProject="src/main/java">
                  <property name="enableSubPackages" value="true"/>
                  <property name="trimStrings" value="true"/>
              </javaModelGenerator>
      
      
              <!--生成映射文件存放位置-->
              <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
                  <property name="enableSubPackages" value="true"/>
              </sqlMapGenerator>
      
              <!--生成Dao类存放位置-->
              <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                      type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                      type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
              <javaClientGenerator type="XMLMAPPER" targetPackage="com.datayang.wp.dao" targetProject="src/main/java">
                  <property name="enableSubPackages" value="true"/>
              </javaClientGenerator>
      
              <!-- table标签可以有多个,至少一个,tableName指定表名,可以使用_和%通配符,我这里的配置表明匹配所有的表 -->
              <table schema="root" tableName="wp_users"  >
                  <!-- 是否只生成POJO对象 -->
                  <property name="modelOnly" value="false"/>
                  <!-- 插入一条数据时,将id映射到实体类中 -->
                  <generatedKey column="id" sqlStatement="mysql" identity="true"/>
              </table>
          </context>
      </generatorConfiguration>
      

2. dao层

自定义MyMapper,作为dao的父类,此文件不要和其他dao文件放一起,防止扫描时有影响,单独建个文件夹。

package com.datayang.wp.config;


import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {

}

3.service 层

package com.datayang.wp.service;

import java.util.List;

import org.springframework.stereotype.Service;

@Service
public interface IService<T> {
    List<T> selectAll();

    T selectByKey(Object key);

    int save(T entity);

    int delete(Object key);

    int updateAll(T entity);

    int updateNotNull(T entity);

    List<T> selectByExample(Object example);
}
package com.datayang.wp.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.datayang.wp.service.IService;

import tk.mybatis.mapper.common.Mapper;

public abstract class BaseService<T> implements IService<T>{
        @Autowired
        protected Mapper<T> mapper;

        public Mapper<T> getMapper() {
            return mapper;
        }

        @Override
        public List<T> selectAll() {
            //说明:查询所有数据
            return mapper.selectAll();
        }

        @Override
        public T selectByKey(Object key) {
            //说明:根据主键字段进行查询,方法参数必须包含完整的主键属性,查询条件使用等号
            return mapper.selectByPrimaryKey(key);
        }

        @Override
        public int save(T entity) {
            //说明:保存一个实体,null的属性也会保存,不会使用数据库默认值
            return mapper.insert(entity);
        }

        @Override
        public int delete(Object key) {
            //说明:根据主键字段进行删除,方法参数必须包含完整的主键属性
            return mapper.deleteByPrimaryKey(key);
        }

        @Override
        public int updateAll(T entity) {
            //说明:根据主键更新实体全部字段,null值会被更新
            return mapper.updateByPrimaryKey(entity);
        }

        @Override
        public int updateNotNull(T entity) {
            //根据主键更新属性不为null的值
            return mapper.updateByPrimaryKeySelective(entity);
        }

        @Override
        public List<T> selectByExample(Object example) {
            //说明:根据Example条件进行查询
            //重点:这个查询支持通过Example类指定查询列,通过selectProperties方法指定查询列
            return mapper.selectByExample(example);
        }
}

运行eclipse里run as -> maven build。mybatis-generator:generate,生成po,xml,dao. dao 层要继承 MyMapper类。service要继承BaseService类,如下代码

package com.datayang.wp.service;

import java.util.List;

import com.datayang.wp.bean.WpUsers;
import com.github.pagehelper.PageInfo;

public interface WpUsersService extends IService<WpUsers> {
    /*
     * 注解方式试例
     */
    List<WpUsers> findAllUser();

    List<WpUsers> findAllByPage(int pageNum, int pageSize);

    PageInfo<WpUsers> findAllByPage2(int pageNum, int pageSize);
    /*
     * xml方式
     */
    WpUsers findUserByName(String uname);
}

package com.datayang.wp.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.datayang.wp.bean.WpUsers;
import com.datayang.wp.dao.WpUsersMapper;
import com.datayang.wp.service.WpUsersService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class WpUsersServiceImpl extends BaseService<WpUsers> implements WpUsersService{

    @Autowired
    private WpUsersMapper wpUsersMapper;

    @Override
    public List<WpUsers> findAllByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<WpUsers> lists = wpUsersMapper.selectAll();
        return lists;
    }

    @Override
    public PageInfo<WpUsers> findAllByPage2(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<WpUsers> lists = wpUsersMapper.selectAll();
        PageInfo<WpUsers> pageInfo = new PageInfo<WpUsers>(lists);
        return pageInfo;
    }

    @Override
    public List<WpUsers> findAllUser() {
        return wpUsersMapper.findAllUser();
    }

    @Override
    public WpUsers findUserByName(String uname) {
        return wpUsersMapper.findUserByName(uname);
    }

}

dao 层

package com.datayang.wp.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.datayang.wp.bean.WpUsers;
import com.datayang.wp.config.MyMapper;

@Mapper
public interface WpUsersMapper extends MyMapper<WpUsers> {

     @Select("SELECT * FROM wp_users")
     List<WpUsers> findAllUser();
     /*
      * xml方式
      */
     WpUsers findUserByName(String name);
}

4. 代码结构

代码结构

参考:
地址1
地址2
地址3
地址4
地址5

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注