SprinBoot 整合 Mybatis

创建SpringBoot项目

e61d3479cdfe4d006f6e6909633ec46ff8d.jpg

500b6a8a4e23ac97f7a5d124778ad344ac7.jpg

f936fbead7f23f77191ebe49fc115d67e5e.jpg

b50fe054ef5f25452c89790b145d7e18533.jpg

57a3c585a364fdb8342d8841cf5b81a2a96.jpg

 

开始配置

一、pom文件配置

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.0.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.17</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.0</version>
</dependency>
<!--freemarker模板-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

项目结构

b0188eafbc5cde1476ddcdb38c58be1d7a4.jpg

application.yml        主要配置文件

#默认使用配置环境
spring:
  profiles:
    active: dev

application-dev.yml        开发环境

#开发环境
server:
  port: 8082

#datasource
spring:
  mvc:
    static-path-pattern: /static/**
    view:
      prefix: /templates/
      suffix: .ftl
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle:
    timeBetweenEvictionRunsMillis: 60000
    minEvictionRunsMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20

    # Redis数据库索引(默认为0)
    redis:
    database: 0
    timeout: 0
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6379
    # 连接池最大连接数(使用负值表示没有限制)
    pool:
      max-active: 8
      # 连接池最大阻塞等待时间(使用负值表示没有限制)
      max-wait: -1
      # 连接池中的最大空闲连接
      max-idle: 8
      # 连接池中的最小空闲连接
      min-idle: 0
    cluster:
      max-redirects: 10
      nodes: 127.0.0.1:6080

#mybatis
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.example.demo.entity
  configuration:
    map-underscore-to-camel-case: true

#showSql
logging:
  level:
    com.example.demo.dao: debug

application-prod.yml      生成环境

application-test.yml        测试环境

 

程序启动类

@SpringBootApplication
@MapperScan("com.example.demo.dao") //扫描的mapper
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

看到这个说明启动成功

1649847ff77d16e35834892670a3b251958.jpg

 

通过mybatis访问数据库

@Autowired
private UserService userService;

@RequestMapping
public String job() {
    return "index";
}

@ApiOperation(value = "获取用户信息", notes = "根据url的id来获取详细信息")
@ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", dataType = "int", required = true, value = "用户id", defaultValue = ""),
})
@GetMapping("/user/{id}")
public User getUser(@PathVariable Integer id, @PathVariable String name) {
    if (id == null) {
        return null;
    }
    return userService.getUser(id);
}

service

@Resource
private UserMapper userMapper;
@Autowired
private RedisJson redisJson;

/**
 * 获取redis的数据
 *
 * @param id
 * @return
 */
public User getUser(Integer id) {
    User user = redisJson.get("user", User.class);
    if (user == null) {
        user = findById(id);
    }
    return user;
}

/**
 * 查询数据库
 * @param id
 * @return
 */
public User findById(Integer id) {
    User user = userMapper.findById(id);
    redisJson.set("user", user);
    return user;
}

dao

public interface UserMapper {
    User findById(Integer id);
}

mapper.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.uwang.hellospringboot.dao.UserMapper">
    <select id="findById"  resultType="user">
        select * from user where id=#{id}
    </select>
</mapper>

 

generatorConfig代码生成器配置

 

<?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">

<generatorConfiguration>
    <!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
    <classPathEntry location="C:\application\lib\mysql-connector-java-5.1.47.jar"/>

    <context id="Tables" targetRuntime="MyBatis3">
        <!-- 注释 -->
        <commentGenerator>
            <!-- 是否生成注释代时间戳 -->
            <property name="suppressDate" value="true"/>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- JDBC连接 -->
        <jdbcConnection
                driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/test?useSSL=false&amp;nullNamePatternMatchesAll=true"
                userId="root"
                password="123456">
        </jdbcConnection>

        <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
         NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="com.example.demo.entity" targetProject="src/main/java">
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true"/>
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </javaModelGenerator>

        <!-- 生成mapper xml文件 -->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 生成mapper xml对应Client-->
        <javaClientGenerator targetPackage="com.example.demo.dao" targetProject="src/main/java"
                             type="XMLMAPPER">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <!-- schema即为数据库名 tableName为对应的数据库表 domainObjectName是要生成的实体类 enable*ByExample
            是否生成 example类 -->

        <table tableName="t_course"
               domainObjectName="Course" enableCountByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               enableUpdateByExample="false">
        </table>
    </context>
</generatorConfiguration>

 

032eca0e3132f34f1292e0c02c52debe163.jpg

19d0c6c289c53bfdebe005671714fa6ba7a.jpg

af9cd7f15bb3a63769bd5d2ff780a7e5c47.jpg            运行即可生成代码

 

转载于:https://my.oschina.net/u/4057956/blog/3052423

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值