SpringBoot笔记(八)MyBatis

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lftaoyuan/article/details/80065710

插件和配置

  • mybatis
  • redis
  • mysql
  • druid

依赖

    <dependencies>
        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <!-- 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>1.3.2</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

配置文件

spring:
    thymeleaf:
        cache: false
    freemarker:
        cache: false
    groovy:
        template.cache: false
    # 数据源
    datasource:
        # 数据库的URL、帐号、密码、驱动
        url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
        # 使用druid连接池
        type: com.alibaba.druid.pool.DruidDataSource
        # druid连接池的配置信息
        initialSize: 5
        # 最小连接数量
        minIdle: 5
        # 最大连接数量
        maxActive: 20
        # 获取连接等待超时的时间
        maxWait: 60000
        # 间隔多久进行一次检测(需要关闭的空闲连接)
        timeBetweenEvictionRunsMillis: 30000
        # 连接在池中最小生存的时间
        minEvictableIdleTimeMillis: 30000
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false

# MyBatis 配置
mybatis:
    # mybatis的mapper.xml文件的路径
    mapper-locations: classpath:mapper/*.xml
    # mybatis的model所在的包
    type-aliases-package: com.jiataoyuan.demo.springboot.model
    # mybatis的model所在的包

编写程序

结构

结构

model

数据库字段对应,id自增即可,自己定义uuid也可以

package com.jiataoyuan.demo.springboot.model;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/4/17 0017
 * @description description
 */
public class User {
    private long id;
    private String name;
    private int age;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

DAO

package com.jiataoyuan.demo.springboot.dao;

import com.jiataoyuan.demo.springboot.model.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/4/17 0017
 * @description description
 *
 */

/*
 * @Repository 也可以不用添加,但是不添加之后使用@Autowired注入接口是IDEA会提示红线,但是不影响编译运行
 * @Mapper 配置自动扫描
 */
@Mapper
public interface UserDao {
    // xml方式
    User findByName(String name);

    // 注解方式
    @Select("select * from user")
    List<User> findAll();

    // 添加用户
    int insertUser(@Param("name")String name, @Param("age")Integer age);


}

Service

package com.jiataoyuan.demo.springboot.service;

import com.jiataoyuan.demo.springboot.dao.UserDao;
import com.jiataoyuan.demo.springboot.model.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/4/17 0017
 * @description description
 */
@Service
public class UserService {

    @Resource
    private UserDao userDao;

    public User findByName(String name){
        return userDao.findByName(name);
    }

    public List<User> findAll(){
        return userDao.findAll();
    }

    public int insertUser(@Param("name")String name, @Param("age")Integer age){
        return userDao.insertUser(name, age);
    }

}

Mapper

<?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">
<!--命名空间,指定对应的Dao-->
<mapper namespace="com.jiataoyuan.demo.springboot.dao.UserDao">

    <!--使用resultType指定输出类型-->
    <select id="findByName" resultType="User">
        SELECT * FROM user WHERE name = #{NAME }
    </select>

    <!-- insert user -->
    <insert id="insertUser" parameterType="com.jiataoyuan.demo.springboot.model.User">
        insert into user ( name, age) values (#{name,jdbcType=VARCHAR}, #{age, jdbcType=INTEGER})
    </insert>
</mapper>

业务逻辑主要就是这3个,接下来需要写接口调用即可

Controller

package com.jiataoyuan.demo.springboot.controller;

import com.jiataoyuan.demo.springboot.model.User;
import com.jiataoyuan.demo.springboot.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author TaoYuan
 * @version V1.0.0
 * @date 2018/4/16 0016
 * @description description
 */
@RestController
@RequestMapping("/db")
public class DBController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @GetMapping()
    public String Main(){
        return "Welcome to DB Page!";
    }

    @GetMapping("/find/{name}")
    public User findByName(@PathVariable String name){
        return userService.findByName(name);
    }

    @GetMapping("/findall")
    public List<User> findAll(){
        return userService.findAll();
    }

    @GetMapping("/insert/{name}/{age}")
    public int insert(@PathVariable String name, @PathVariable Integer age){
        logger.warn("name =="+ name);
        logger.warn("age =="+ age);

        return userService.insertUser(name, age);
    }





}

测试

1

2

接下来准备redis

MyBatis生成插件

<!-- mybatis maven插件 -->
<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.5</version>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
        <dependency>
            <groupId>com.xxg</groupId>
            <artifactId>mbg-limit-plugin</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    <configuration>
        <overwrite>true</overwrite>
    </configuration>
</plugin>

build上面加上这个,不然找不到mbg-limit-plugin

<pluginRepositories>
    <pluginRepository>
        <id>xxg-repository</id>
        <url>http://repo.maven.xxgblog.com/</url>
    </pluginRepository>
</pluginRepositories>

这个文件放在resources下并进行修改

generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- mybatis生成配置 -->
<!-- 最后一行table元素中修改自己的要生成的表名及实体名称 -->
<!--用法: 选择pom.xml文件,击右键先择Run AS——Maven Build… ——在Goals框中输入:mybatis-generator:generate——Run就好了,在工程上刷新-->

<generatorConfiguration>
  <context id="call" targetRuntime="MyBatis3" defaultModelType="hierarchical">

    <plugin type="com.xxg.mybatis.plugins.MySQLLimitPlugin"></plugin>
    <!-- 数据库连接信息 -->
    <!-- <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://172.16.127.201:3306/kaikeba?useUnicode=true&amp;characterEncoding=utf-8"
        userId="test"
        password="Meihao100@bfbd">
    </jdbcConnection> -->

    <commentGenerator>
      <!-- 是否去除自动生成的注释 true:是 : false:否 -->
      <property name="suppressAllComments" value="true" />
    </commentGenerator>

    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/test"
        userId="root"
        password="123456">
    </jdbcConnection>

    <!-- model实体类 -->
     <javaModelGenerator targetPackage="com.jiataoyuan.demo.springboot.model" targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <!-- sql xml -->
    <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

    <!-- dao -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.jiataoyuan.demo.springboot.dao" targetProject="src/main/java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

    <!-- 表名, 生成的实体名 -->

    <table tableName="user" domainObjectName="User"
           enableDeleteByExample="false" enableDeleteByPrimaryKey="false">
      <!--<columnOverride column="operate_next_flag" javaType="int"/>-->
      <!--<columnOverride column="is_delete" javaType="int"/>-->
    </table>

</context>
</generatorConfiguration>

  • 注释部分几乎不用管
  • 数据库地址改成自己的
  • model实体类改成自己的model包名
  • sql xml 指定生成的Mapper.xml
  • dao改成自己的dao包名
  • 表名改成需要生成的model bean,可以设置字段类型等,多个表则建立多个table标签
  • 如果已经有mapper.xml了,把之前的名字改了,否则会覆写

然后打开maven project进行生成操作

生成操作

自己写虽然麻烦,但是定制化程度高,自动生成简单,也可以改,其实也并不存在太多的定制化,生成后也可以自己改,总之还是看自己的习惯吧。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页