SpringBoot整合Mybatis

时间:2019-12-14
本文章向大家介绍SpringBoot整合Mybatis,主要包括SpringBoot整合Mybatis使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.导入依赖

   <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

2.创建实体类

3.Dao层

4.Service层

5.ServiceImpl层

package com.my.service.impl;
import com.my.dao.IStudentDao;
import com.my.entity.Student;
import com.my.service.StudentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("studentService")
public class StudentServiceImpl implements StudentService {
    @Resource
    private IStudentDao iGradeDao;


    @Override
    public int insertGrade(Student grade) {
        return iGradeDao.insertGrade(grade);
    }

    @Override
    public int updateGrade(Student grade) {
        return iGradeDao.updateGrade(grade);
    }

    @Override
    public int deleteGrade(Integer id) {
        return iGradeDao.deleteGrade(id);
    }

    @Override
    public List<Student> findAll() {
        return iGradeDao.findAll();
    }
}
View Code

6.Controller层

package com.my.controller;


import com.my.entity.Student;
import com.my.service.StudentService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class MybatisController {
    @Resource(name = "studentService")
    private StudentService studentService;

    @RequestMapping("/insertGrade")
    public int insertGrade(){
        return studentService.insertGrade(new Student("S1"));
    }

    @RequestMapping("/updateGrade")
    public int updateGrade(){
        return  studentService.updateGrade(new Student(10012,"S2"));
    }

    @RequestMapping("/deleteGrade")
    public int deleteGrade(){
        return studentService.deleteGrade(10012);
    }

    @RequestMapping("/findAll")
    public List<Student> findAll(){
        return studentService.findAll();
    }
}
View Code

7.resources配置文件

  mapper

    Dao.xml

<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTDMapper3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.my.dao.IStudentDao"><resultMapid="getmap"type="com.my.entity.Student"><idproperty="stu_id"column="stu_id"></id><resultproperty="stu_name"column="stu_name"></result></resultMap><insertid="insertGrade">insertintostudentinfo(stu_name)values(#{stu_name})</insert><!--修改数据--><updateid="updateGrade">updatestudentinfosetstu_name=#{stu_name}wherestu_id=#{stu_id}</update><!--删除数据--><deleteid="deleteGrade">deletefromstudentinfowherestu_id=#{stu_id}</delete><!--查询数据--><selectid="findAll"resultType="com.my.entity.Student">select*fromstudentinfo</select></mapper>
增删改查

application.yml

原文地址:https://www.cnblogs.com/mayuan01/p/12039070.html