SpringBoot整合Mybatis
1、 导入mybatis相关依赖
<!-- spring-boot mabatis依赖 不要使用1.0.0版本,因为1.0.0版本还不支持拦截器插件 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.0</version> </dependency>
2、编写Mapper接口
@Mapper public interface EmployeeMapper{ //根据id查询 public Employee queryById(int empno) throws Exception; //查询指定页数据 public List<Employee> queryByPage(@Param("start")int start, @Param("pageSize") int pageSize) throws Exception; // 添加员工 public void add(Employee emp) throws Exception; }
3、编写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.zl.app.mapper.EmployeeMapper"> <select id="queryById" resultType="Employee"> select * from emp where empno = #{empno} </select> <select id="queryByPage" resultType="Employee"> <!-- 如果是多个参数, 默认写法: param1, param2--> <!-- select * from emp limit #{param1} ,#{param2} --> <!-- 多个参数: Mapper映射文件写的参数名, 需要在Mapper接口对应方法上添加一个注解: --> select * from emp limit #{start} ,#{pageSize} </select> <insert id="add" parameterType="Employee"> INSERT INTO `emp` (`empno`,`ename`,`job`,`mgr`,`hiredate`,`sal`,`comm`,`deptno`) VALUES ( #{empno,jdbcType=INTEGER},#{ename,jdbcType=VARCHAR}, //指定数据类型防止空指针异常 #{job,jdbcType=VARCHAR},#{mgr,jdbcType=INTEGER}, #{hiredate,jdbcType=DATE},#{sal,jdbcType=DECIMAL}, #{comm,jdbcType=DECIMAL},#{deptno,jdbcType=INTEGER} ) </insert> </mapper>
4、SpringBoot的配置文件(application.yml)中配置mybatis相关的配置
#mybatis的配置
mybatis:
type-aliases-package: com.zl.app.entity
mapper-locations: classpath*:mapper/*Mapper.xml
5、在启动类添加一个@MapperScan() 扫描@Mapper注解 (可以省略)
@SpringBootApplication @MapperScan("com.zl.app.mapper") public class SpringBoot05JdbcDemoApplication { public static void main(String[] args) { SpringApplication.run(SpringBoot05JdbcDemoApplication.class, args); }
如果启动类位于父包下,可以省略, 不在父包,一定不能省略