spring-boot-mybatis

2020-08-30  本文已影响0人  Shawn_Shawn

Spring-boot-mybatis

  1. sql

    DROP TABLE IF EXISTS `t_menu`;
    CREATE TABLE `t_menu`
    (
        `menu_id`   bigint       NOT NULL AUTO_INCREMENT,
        `parent_id` bigint       NOT NULL COMMENT '父菜单ID,一级菜单为0',
        `name`      varchar(50)  NOT NULL COMMENT '菜单名称',
        `url`       varchar(200) NOT NULL COMMENT '菜单URL',
        `level`     int(2)       NOT NULL,
        `type`      int          NOT NULL COMMENT '类型   0:目录   1:菜单   2:按钮',
        `order` int          NOT NULL COMMENT '排序',
        PRIMARY KEY (`menu_id`)
    ) ENGINE = `InnoDB`
      DEFAULT CHARACTER SET utf8mb4 COMMENT ='菜单管理';
    
  2. pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <parent>
        <artifactId>springboot</artifactId>
        <groupId>com.shawn</groupId>
        <version>1.0-SNAPSHOT</version>
      </parent>
      <modelVersion>4.0.0</modelVersion>
    
      <artifactId>spring-boot-mybatis-demo</artifactId>
    
      <dependencies>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
          <groupId>org.mybatis.spring.boot</groupId>
          <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
        </dependency>
      </dependencies>
    
      <build>
        <resources>
          <resource>
            <directory>src/main/java</directory>
            <includes>
              <include>
                **/*.xml
              </include>
            </includes>
          </resource>
        </resources>
      </build>
    </project>
    
  3. application.yaml

    spring.datasource.url: jdbc:mysql://127.0.0.1:3306/spring-boot-demo?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
    spring.datasource.username: root
    spring.datasource.password: 11111
    spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
    
    mybatis.configuration.map-underscore-to-camel-case: true # 开启驼峰式命名
    mybatis.mapper-locations: classpath:mappers/*.xml # 配置mapper.xml
    mybatis.type-aliases-package: com.shawn.spring.boot.mybatis.entity # 省略实体类的报名
    mybatis.type-handlers-package: com.shawn.spring.boot.mybatis.handle # 添加处理器
    
  4. 实体类

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class Menu {
    
      private long menuId;
      private long parentId;
      private String name;
      private String url;
      private int level;
      private MenuTypeEnum type; // 枚举
      private int order;
    }
    
    public interface BaseEnum {
    
      int getCode();
    
      String getName();
    
    }
    
    public enum MenuTypeEnum implements BaseEnum {
      CATALOG_TYPE(0, "目录"),
      MENU_TYPE(1, "菜单"),
      BUTTON_TYPE(2, "按钮");
    
      private int code;
      private String name;
    
      MenuTypeEnum(int code, String name) {
        this.code = code;
        this.name = name;
      }
    
      @Override
      public int getCode() {
        return code;
      }
    
      @Override
      public String getName() {
        return name;
      }
    }
    
  5. mapper

    @Mapper
    @Repository
    public interface MenuMapper {
    
      @Insert(
          "insert into t_menu (`parent_id`, `name`, `url`, `level`, `type`, `order`) values "
              + " (#{menu.parentId}, #{menu.name}, #{menu.url}, #{menu.level}, #{menu.type}, #{menu.order})")
      @Options(useGeneratedKeys = true)
      int insert(@Param("menu") Menu menu);
    
      int update(@Param("menu") Menu newMenu);
    
      @Delete("delete from t_menu where menu_id = #{id}")
      int delete(@Param("id") long id);
    
      @Select("select * from t_menu")
      List<Menu> selectAll();
    
      @Select("SELECT * FROM t_menu WHERE menu_id = #{id}")
      Menu selectById(@Param("id") Long id);
    }
    
    <!-- 在resources/mappers 目录下创建一个xml文件 -->
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.shawn.spring.boot.mybatis.mapper.MenuMapper">
    
      <update id="update" parameterType="Menu">
        update `t_menu` set `name` = #{menu.name},
        `url` = #{menu.url},
        `level` = #{menu.level},
        `type` = #{menu.type},
        `order` = #{menu.order}
        where `menu_id` = #{menu.menuId}
      </update>
    
    </mapper>
    
  6. service

    @Service
    public class MenuServiceImpl implements MenuService {
    
      @Autowired private MenuMapper mapper;
    
      @Override
      public void insert(Menu menu) {
        mapper.insert(menu);
      }
    
      @Override
      public void update(Menu menu) {
        mapper.update(menu);
      }
    
      @Override
      public void delete(long id) {
        mapper.delete(id);
      }
    
      @Override
      public List<Menu> findAll() {
        return mapper.selectAll();
      }
    
      @Override
      public Menu findById(long id) {
        return mapper.selectById(id);
      }
    }
    
  7. handle

    // enum类型处理器(暂时不通用)
    public class EnumTypeHandler<E extends Enum<?> & BaseEnum> extends BaseTypeHandler<BaseEnum> {
    
      @Override
      public void setNonNullParameter(
          PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getCode());
      }
    
      @Override
      public BaseEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int code = rs.getInt(columnName);
        return rs.wasNull() ? null : EnumUtil.codeOf(MenuTypeEnum.class, code);
      }
    
      @Override
      public BaseEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int code = rs.getInt(columnIndex);
        return rs.wasNull() ? null : EnumUtil.codeOf(MenuTypeEnum.class, code);
      }
    
      @Override
      public BaseEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int code = cs.getInt(columnIndex);
        return cs.wasNull() ? null : EnumUtil.codeOf(MenuTypeEnum.class, code);
      }
    }
    
  8. runner

    @Component
    @Slf4j
    public class MybatisRunner implements ApplicationRunner {
    
      @Autowired private MenuService service;
    
      @Override
      public void run(ApplicationArguments args) throws Exception {
        log.info("test insert");
        testInsert();
        log.info("test update");
        testUpdate();
        log.info("test find all");
        testFindAll();
        log.info("test find by id");
        testFindById();
        log.info("test delete");
        testDelete();
        log.info("test find by id");
        testFindById();
      }
    
      private void testInsert() {
        Menu menu =
            Menu.builder()
                .parentId(0)
                .name("test")
                .level(1)
                .type(MenuTypeEnum.CATALOG_TYPE)
                .url("/test")
                .order(1)
                .build();
        service.insert(menu);
      }
    
      private void testUpdate() {
        Menu newMenu =
            Menu.builder()
                .menuId(1)
                .name("test2")
                .level(2)
                .type(MenuTypeEnum.CATALOG_TYPE)
                .url("/test2")
                .order(2)
                .build();
        service.update(newMenu);
      }
    
      private void testDelete() {
        service.delete(1);
      }
    
      private void testFindAll() {
        service.findAll().forEach(menu -> log.info(menu.toString()));
      }
    
      private void testFindById() {
        Menu menu = service.findById(3);
        if (menu == null) {
          log.warn("not found, id: {}", 3);
        } else {
          log.info(menu.toString());
        }
      }
    }
    
  9. main class

    @SpringBootApplication
    @MapperScan("com.shawn.spring.boot.mybatis.mapper")
    public class MybatisApplication {
    
      public static void main(String[] args) {
        SpringApplication.run(MybatisApplication.class, args);
      }
    }
    
上一篇下一篇

猜你喜欢

热点阅读