springboot2.0與mybatis整合

    mybatis爲了自動適配springboot開發適配包,需要引入

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis‐spring‐boot‐starter</artifactId>
    <version>2.1.2</version>
</dependency>

可以使用2種方式整合

一、註解方式,直接在dao上註解

@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id=#{id}")
    public Department getDeptById(Integer id);

    @Delete("delete from department where id=#{id}")
    public int deleteDeptById(Integer id);

    @Options(useGeneratedKeys = true, keyProperty = "id")
    @Insert("insert into department(departmentName) values(#{departmentName})")
    public int insertDept(Department department);

    @Update("update department set departmentName=#{departmentName} where id=#{id}")
    public int updateDept(Department department);
}

備註:需要加入@Mapper才能被掃描到或者在全局(SpringbootmybatisApplication)上進行配置@MapperScan(value = "com.cax.springboot.mapper")

二、使用配置文件方式

使用該方式實現需要指定xml實現文件

mybatis:
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
@Mapper
public interface EmployeeMapper {

    public Employee getEmployeeById(Integer id);
    
}

xml文件內容如下

<?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.cax.springboot.mapper.EmployeeMapper">
    <select id="getEmployeeById" parameterType="Integer" resultType="com.cax.springboot.entry.Employee">
        select * from employee where id = #{id}
    </select>
</mapper>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章