1. 在pom.xml文件中添加mybatis和mybatis-spring-boot-starter依赖:
<dependencies>
    <!--其他依赖-->
    <!--mybatis依赖-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <!--mybatis-spring-boot-starter依赖-->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
</dependencies>
  1. 在application.properties文件中配置mybatis:
#mybatis配置
mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*.xml
  1. 创建mybatis-config.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

其中,mapUnderscoreToCamelCase设置为true可以让驼峰命名和下划线命名自动转换。

  1. 创建Mapper接口和对应的Mapper.xml文件:
public interface UserMapper {
    User selectUserById(Integer id);
}
<?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.example.mapper.UserMapper">
    <select id="selectUserById" parameterType="java.lang.Integer" resultType="com.example.entity.User">
        select * from user where id = #{id}
    </select>
</mapper>
  1. 在Service中使用Mapper:
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User selectUserById(Integer id) {
        return userMapper.selectUserById(id);
    }
}
  1. 在Controller中调用Service:
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User selectUserById(@PathVariable Integer id){
        return userService.selectUserById(id);
    }
}

以上就是在idea的springboot项目中导入mybatis的步骤。

怎么在idea的springboot项目中导入mybatis

原文地址: http://www.cveoy.top/t/topic/bVTz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录