1、首先搭建起Spring Boot Web项目
链接地址https://mp.csdn.net/postedit/101756693
2、引入jar包
<!-- mybatis开始 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<!--<scope>runtime</scope>-->
</dependency>
<!-- mybatis结束 -->
3、引入配置文件
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml
type-aliases-package: com.example.demo
4、创建数据库和表
create table springboot.user
(
id bigint not null AUTO_INCREMENT comment '主键' primary key,
age int null comment '年龄',
password varchar(32) null comment '密码',
sex int null comment '性别',
username varchar(32) null comment '用户名'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
5、扫描mapper层
6、mapper层
@Repository
public interface UserMapper {
User Sel(int id);
}
7、service层
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User Sel(int id) {
return userMapper.Sel(id);
}
}
8、entity层
public class User {
private Integer id;
private String userName;
private String passWord;
private String realName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", realName='" + realName + '\'' +
'}';
}
}
9、UserMapper.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.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="userName" jdbcType="VARCHAR" property="userName" />
<result column="passWord" jdbcType="VARCHAR" property="passWord" />
<result column="realName" jdbcType="VARCHAR" property="realName" />
</resultMap>
<select id="Sel" resultType="com.example.demo.entity.User">
select * from user where id = #{id}
</select>
</mapper>
10启动项目则可以访问该接口
//访问/hello或者/hi任何一个地址,都会返回一样的结果
@RequestMapping(value = {"/getUser"}, method = RequestMethod.GET)
public String getUser(@RequestParam Integer id) {
if (id==null)
return null;
return userService.Sel(id).toString();
}