Springboot整合Myabits

第一步新建一个springboot项目

Springboot整合Myabits_第1张图片
Springboot整合Myabits_第2张图片

第二步导入mybaits架包

  <!--mybaits插件-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

第三步编写application.yml文件

server:
  port: 8081
spring:
  datasource:
    # MySql
    url: jdbc:mysql://121.4.40.38:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
    username: root
    password: 123456
#整合mybatis
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.mw.pojo

第四步编写实体类和mapper层 controller层

实体类

package com.mw.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
public class User {
     
    private Integer id;
    private String  name;
    private Integer sex;
    private Integer age;
}

mapper层
package com.mw.mapper;

import com.mw.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface UserMapper {
//查询全部用户
List queryUserlist();
//根据用户id查询用户
User queryUserById(int id);
//根据id删除用户
int deleteUser(int id);
//添加用户
int addUser(User user);
//修改用户
int updateUser(User user);
}

controller层

package com.mw.controller;

import com.mw.mapper.UserMapper;
import com.mw.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserController {
     
    @Autowired
    private UserMapper userMapper;
    @GetMapping("/index")
    public List<User>  queryUserlist(){
     
        List<User> users = userMapper.queryUserlist();
        return users;
    }
}

mapper层sql

<?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.mw.mapper.UserMapper">
    <select id="queryUserlist" resultType="com.mw.pojo.User">
        select * from user
    </select>
</mapper>

启动项目访问项目

http://localhost:8081/index
Springboot整合Myabits_第3张图片

你可能感兴趣的:(mybatis,spring,boot)