Springboot整合Myabits

MW0309發表於2021-01-02

第一步新建一個springboot專案

在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

第二步匯入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
在這裡插入圖片描述

相關文章