2019-04-15 SpringBoot+MyBatis+MySQL

使用全注解的方式实现SpringBoot,MyBatis,MySQL的整合
1.新建User表


image.png

2.pom.xml依赖配置

        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.1
        
        
        
            mysql
            mysql-connector-java
            runtime
        

3.application.properties中添加MySQL配置

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

4.User类

package com.capgemin.springboot12.pojo;

public class User {
    private Integer id;
    private String name;

    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;
    }
}

5.DAO层

package com.capgemin.springboot12.mapper;

import com.capgemin.springboot12.pojo.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;

import java.util.List;

@Mapper
@Component
public interface UserMapper {
    /**
     * 添加操作
     */
    @Insert("insert into user(id,name) values(#{id},#{name})")
    void insert(User user);

    /**
     * 删除操作
     */
    @Delete("delete from user where id = #{id}")
    Long delete(@Param("id") Integer id);

    /**
     * 更新操作
     */
    @Update("update user set name=#{name},id = #{id}")
    Long update(User user);

    /**
     * 查询所有
     */
    @Select("select * from user")
    List selectAll();

    /**
     * 根据id查询
     */
    @Select("select * from user where id = #{id}")
    User selectById(@Param("id") Integer id);
}

6.Controller层

package com.capgemin.springboot12.controller;

import com.capgemin.springboot12.mapper.UserMapper;
import com.capgemin.springboot12.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

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

    @RequestMapping("/selectAll")
    public List selectAll(){
        return userMapper.selectAll();
    }
}

这里只写了一个selectAll()方法。
7.测试
启动项目,在浏览器地址栏输入:http://localhost:8080/user/selectAll

image.png

你可能感兴趣的:(2019-04-15 SpringBoot+MyBatis+MySQL)