SpringBoot整合Mybatis

96 阅读1分钟

这是我参与11月更文挑战的第22天,活动详情查看:2021最后一次更文挑战

配置版

首先导入一个jar

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

通过这个导入,已经给我们配置许多东西,我们只需要简单的配置一下就行了,

我们之前写Mybatis,需要一个全局配置文件,我们需要在yaml文件中指定一下全局配置文件的位置

在我们的资源包下创建一个mybatis文件夹

写一下我们的全局配置文件

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.rog//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

准备一张表,我们的表是这样的

写好对应表的实体类

具体的不展示了

写一下Mapper接口

@Mapper
public interface AccountMapper {
    /**
     * 获取数据
     * @return
     */
    public Account getAcct();
}

接口写完之后我们去写一下sql.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.springboot01.mapper.AccountMapper">
    <select id="getAcct" resultType="com.example.springboot01.bean.Account">
        select * from account where name = #{name}
    </select>
</mapper>

这两个文件都写完,我们在我们的配置文件中配置我们mybatis的规则

#配置mybatis规则
mybatis:
  config-location: classpath:mybatis/mybatis_config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml

我们使用Service来调用mapper

@Service
public class AccountService {

    @Autowired
    AccountMapper accountMapper;

    public Account getAcctByName(String name){
        return accountMapper.getAcct(name);
    }

}

最后写一下controller层

	@Autowired
    AccountService accountService;

    @GetMapping("/account")
    public Account getByName(@RequestParam("name") String name){

        return accountService.getAcctByName(name);
    }

使用postman测试一下

注解版

创建一个新表

使用了Lombok,就不写其他方法了。

和刚刚流程一样,写mapper类,不需要写xml文件,我们就在上面添加注解

@Mapper
public interface CarMapper {

    /**
     * @param Id
     */
    @Select("select * from car where id=#{id}")
    public Car getById(int Id);
}

编写Service层

@Service
public class CarService {

    @Autowired
    CarMapper carMapper;
    public Car getCarById(int id){
        return carMapper.getById(id);
    }
}

controller层

	@Autowired
    CarService carService;
    @GetMapping("/car")
    public Car getCarById(@RequestParam("id") int id){
        return carService.getCarById(id);
    }

测试代码其实都差不多