两个配置文件:如图所示,在resources文件夹下创建两个配置文件,可以放在不同的目录下面,最后会在yml配置文件中指定路径
mybatis-config.xml:
<?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> </configuration>
mybatis-mapper.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.zhg.mybatis.springbootmybatis.mapper.ScoreMapper"> <select id="selectById" resultType="com.zhg.mybatis.springbootmybatis.bean.Score"> select * from score where id = #{id} </select> <insert id="insertScore" >#这里没有返回一个bean对象,就不用添加resultType了 insert into score (math,chinese) values(#{math},#{chinese}) </insert> </mapper>
注意:
namespace中的包路径,用的时全名(com.zhg.mybatis.springbootmybatis.mapper.ScoreMapper),以及resultType都是用的包全名(com.zhg.mybatis.springbootmybatis.bean.Score)
application.yml配置文件写法:指定mybatis配置文件的路径
mybatis:
config-location: classpath:mybatis/config/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
写mapper方法:
ScoreMapper.java:
package com.zhg.mybatis.springbootmybatis.mapper; import com.zhg.mybatis.springbootmybatis.bean.Score; /** * @author zhuhonggen * @version 创建时间:2019/08/05 11:02 * @ClassName 类名称 * @Description 类描述 */ public interface ScoreMapper { public Score selectById(Integer id); }
ScoreControler.java:
package com.zhg.mybatis.springbootmybatis.controler; import com.zhg.mybatis.springbootmybatis.bean.Score; import com.zhg.mybatis.springbootmybatis.mapper.ScoreMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author zhuhonggen * @version 创建时间:2019/08/05 11:03 * @ClassName 类名称 * @Description 类描述 */ @RestController public class ScoreControler { @Autowired ScoreMapper scoreMapper;
//接口形式:http://127.0.0.1:8080/score/select?id=5 @RequestMapping("/score/select") public Score selectById(@RequestParam("id") Integer id){ Score score = scoreMapper.selectById(id); // String info = String.format("%s", score.toString()); return score; } }
效果: