SpringBoot整合Mybatis

2021-04-24 22:29

阅读:553

标签:doctype   red   tis   指定   star   group   pat   根据   values   

1、 导入mybatis相关依赖


dependency>
    groupId>org.mybatis.spring.bootgroupId>
    artifactId>mybatis-spring-boot-starterartifactId>
    version>1.2.0version>
dependency> 

2、编写Mapper接口

@Mapper
public interface EmployeeMapper{
    //根据id查询
    public Employee  queryById(int empno) throws Exception;
    //查询指定页数据
    public List  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">
        
        
        
        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);
    }

如果启动类位于父包下,可以省略, 不在父包,一定不能省略

SpringBoot整合Mybatis

标签:doctype   red   tis   指定   star   group   pat   根据   values   

原文地址:https://www.cnblogs.com/64Byte/p/13261776.html


评论


亲,登录后才可以留言!