Springboot整合mybatis开发思路

步骤一:添加依赖

        添加MYSQL和mybatis依赖整合SpringBoot框架的依赖

Springboot整合mybatis开发思路_第1张图片

         对于sqlserver用户来说,这样写

Springboot整合mybatis开发思路_第2张图片

            值得一说的有两点:

                        1)数据库依赖不需要添加版本号,因为父模块已经为你设置好了默认的版本号,对于GAV坐标,我们只需要写GA坐标就好

                        2)mybatis的依赖可能是会报错(至少我报错了,说没找到can't resolve),所以我们可以写成:

        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.1
        

 步骤二:依赖中加入使得mapper映射文件在target中还是可以和mapper.class文件在同一个目录下

原因分析:由于IDEA要求mapper.xml文件和mapper文件必须在同一个目录之下,并且配制文件都要放在resources目录之下,所以为了解决问题,我们需要在build标签内部加上这样一段依赖(再次强调:build标签内部,别问我为什么这么强调,问多了都是泪)


            
                src/main/java
                
                    
                        **/*.xml
                    
                
            

 表示从src/main/java目录下的所有的配置文件都要原封不动的安装到target相应的位置,从该java子包到该子包的子包中的所有的任何类型的xml文件,都要遵循上面的规则.这样一来即可解决问题

步骤三:application.properties文件的配制

我们需要配制四个内容:

spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.password=123
spring.datasource.username=sa
spring.datasource.url=jdbc:sqlserver://localhost:1433;database=sa

步骤四:写一个Controller类拦截请求

package com.bjpowernode.springboot.web;

import com.bjpowernode.springboot.model.Student;
import com.bjpowernode.springboot.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class StudentController {
    @Autowired
    private StudentService studentService;

    @RequestMapping(value="/student")
    public @ResponseBody Object student(Integer id)
    {
        Student student=studentService.queryById(id);
        return student;
    }
}

 在这个拦截的过程中,我们需要自动装配studentService对线到IOC容器中,调用这个对象的service方法,返回Student对象

步骤五:使用同样的方法装配Mapper对象,调用接口实现类

Springboot整合mybatis开发思路_第3张图片

 有时候IDEA会犯病,这个bug其实也不用管,我的重启后就解决了.

步骤六:使用@Mapper注解标识接口,扫描到springboot整合容器之中,相比于以前的组件扫描器扫描,这种注解式开发效率更高

package com.bjpowernode.springboot.mapper;

import com.bjpowernode.springboot.model.Student;
import org.apache.ibatis.annotations.Mapper;

@Mapper         //扫描DAO接口到spring容器之中,
public interface StudentMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

总结:过程思考

    浏览器发起请求,为了使得控制层可以获取到service对象,我们需要使用@Service注解,controller对象调用studentService对象,返回student对象,在这个调用的过程中我们使用了mapper层(dao层)对象的方法,所以我们需要提前装配,所以需要加上@Autowired注解.同理在mapper对象调用方法之前,我们需要扫描该dao层方法到springboot容器中,不然它也不知道有哪些dao方法.最后一层,我们需要在application.properties文件中配制最基本的连接数据库的参数,不然鬼知道连接的是哪个数据库.

    

你可能感兴趣的:(springboot学习,mysql,spring,boot,java,sqlserver)