Spring Boot教程
作者: 时海
SpringBoot集成Mybatis第一个Example

1、配置文件

application.yml

spring:
  profiles:
    active: dev
application-dev.yml
server:
  port: 8080

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.example.boot

logging:
  level:
    com:
      example:
        boot: debug

2、业务逻辑

User.java

package com.example.boot;

import java.io.Serializable;

public class User implements Serializable {
    private Integer id;
    private String name;
    private Integer age;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
UserMapper.java
package com.example.boot;

import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper {
    User getUser(int id);
}
UserController.java
package com.example.boot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @RequestMapping("/get/{id}")
    public User getUser(@PathVariable int id) {
        User user = userMapper.getUser(id);
        return user;
    }
}
3、Mybatis配置文件

mapper/UserMapper.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.example.boot.UserMapper">

    <resultMap id="BaseResultMap" type="com.example.boot.User">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="age" jdbcType="INTEGER" property="age" />
    </resultMap>

    <select id="getUser" resultType="com.example.boot.User">
        select * from user where id = #{id}
    </select>

</mapper>

4、主类

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.example.boot")
@SpringBootApplication(scanBasePackages = {"com.example.boot"})
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

4、测试

浏览器中输入:http://localhost:8080/user/get/1

返回:

{"id":1,"name":"zhansan","age":30}



一个创业中的苦逼程序员
  • 回复
隐藏