已有 SpringBoot 程序能够响应前端浏览器HTTP
请求 SQL 能够读取MySQL 数据库数据
缺少 SQL 读取出来的数据转为SpringBoot 程序能够使用的Java 类对象
MyBatis 读取MySQL 数据库数据,将数据转为Java 类对象,供SpringBoot 程序使用
1.确定需求
前端访问后端URL,显示后端从数据库读取的数据
输入:前端访问URL为http://localhost:8080/helloFromDB
输出:前端显示后端从数据库读取的数据
postman中的显示
Mysql数据库表
2.新建项目的子模块
这边正常next
web中勾选Spring Web
SQL中勾选MyBatis Framework和MySQL Driver
create
3.MySQL 数据库配置、添加数据
打开NaviCat新建数据库编写表单
4.编写代码 编译代码、构建程序
1.新建controller、service、mapper、domain 包
2. 新建mapper 资源目录
3. 新建controller、service、mapper、domain 对应的Java 文件
Controller:
package com.example.mybatis.controller; import com.example.mybatis.domain.User; import com.example.mybatis.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class HelloController { @Autowired private UserService userService; @GetMapping("/hello") public List<User> hello() { return userService.selectAllUser(); } }
Service:
package com.example.mybatis.service; import com.example.mybatis.domain.User; import com.example.mybatis.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserService { @Autowired private UserMapper userMapper; public List<User> selectAllUser() { return userMapper.selectAllUser(); } }
Mapper:
package com.example.mybatis.mapper; import com.example.mybatis.domain.User; import java.util.List; public interface UserMapper { public List<User> selectAllUser(); }
Domain:
package com.example.mybatis.domain; public class User { public int id; private String name; private int age; public int sex; public String createTime; public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getCreateTime() { return createTime; } public void setCreateTime(String createTime) { this.createTime = createTime; } }
4.新建mapper 资源目录Java 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.example.mybatis.mapper.UserMapper">
<resultMap id="UserResult" type="User">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="age" column="age" />
<result property="sex" column="sex" />
<result property="createTime" column="create_time" />
</resultMap>
<select id="selectAllUser" resultMap="UserResult">
select * from user
</select>
</mapper>
5. 配置数据库连接和MyBatis
新建yml文件
6.添加必要的注解
7.run就完了
5.测试SpringBoot 后端接口
测试就和上面的效果一样了~