application.yml的配置:
server:
port: 8888
spring:
application:
name: MybatisDemo
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
mybatis:
type-aliases-package: com.wan.model
mapper-locations:
- mapper/*
mybatis-config.xml配置信息:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<typeAliases>
<package name="com.wan.model"/>
</typeAliases>
<mappers>
<mapper resource="mapper/mysql.xml"/>
</mappers>
</configuration>
mysql.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.wan">
<select id="getUserCount" resultType="Integer">
select count(1) from user;
</select>
</mapper>
Class Demo:
package com.wan.controller;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Demo {
@Autowired
private SqlSessionTemplate template;
@GetMapping("/getCount")
public int getUserCount() {
return template.selectOne("getUserCount");
}
}
启动应用 访问:[http://localhost:8888/getCount] 查询到的user个数为2