<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency>
如何告訴Spring容器,哪一個接口是Mapper呢?html
通常咱們的都是單首創建一個mapper的packet, 閒麻煩能夠選擇使用@Mapper
註解標記在單個mapper接口上,或者使用@MapperScan
完成mapper的批量掃描java
完成簡單註解版的CURDspring
方法的名字見名知意就行,可是方法的返回值得是註解上sql對應的返回值sql
@Select
@Select("select * from person where id=#{id}") public Person getPersonById(Integer id);
@Delete
@Delete("delete from person where id = #{id}") public int deletePersonById(Integer id);
@Insert
// 添加Options註解,指定主鍵自增加, keyProperty 指定主鍵是誰,效果是運行完insert語句後,id會封裝進被插入的對象中 // 方便咱們後續接着使用 @Options(useGeneratedKeys = true,keyProperty = "id") @Insert("insert into person (name,password) values(#{name},#{name})") public int insertPerson(Person person);
@Update
@Update("update person set name=#{name} , password=#{password} where id=#{id}") public int updatePerson(Person person);
點擊進入MyBatis3官網apache
以下圖所示,在Resources目錄下面建立指定的配置文件mybatis
配置文件的內容在上面的官網上能夠找到,個人以下app
mybatis-config.xmlspring-boot
點擊查看更多的配置spa
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="useGeneratedKeys" value="true"/> </settings> </configuration>
MyBankMapper.xmlcode
<?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.changwu.mapper.MyBankMapper"> <select id="getMyBankById" resultType="com.changwu.pojo.MyBank"> select * from mybank where id = #{id} </select> <insert id="insertMyBank"> insert into mybank (username, password, money) values (#{username},#{password},#{money}) </insert> </mapper>
經過在application.yml
中添加配置告訴SpringBoot去哪裏讀取配置文件
mybatis: config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
原文出處:https://www.cnblogs.com/ZhuChangwu/p/11656114.html