环境版本
Mysql-8.0
springboot-2.1.6
jdk-1.8
1.新建项目
2.采用mybatis-generator自动生成mapper,dao,entity
连接:https://www.jianshu.com/p/b519e9ef605f
3.配置application.properties
文件
server.port=8080
# ==============================
# MySQL connection config
# ==============================
spring.datasource.url=jdbc:mysql://localhost:3306/wg_insert?useUnicode=true&characeterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
# ==============================
# Hikari 数据源专用配置
# ==============================
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
# ==============================
# Thymeleaf configurations
# ==============================
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.encoding=UTF-8
# ==============================
# Mybatis configurations
#添加对xml中对实体对象引用的配置
#添加xml在resouces目录下的位置
# ==============================
mybatis.type-aliases-package=com.wglvzyx.mybatisredis.entity
mybatis.mapper-locations=classpath:mapper/*.xml
4.实现查询所有的学生函数功能
-
在
StudentMapper
添加函数List<Student> selectAllStudent();
注意在IDEA中需要给这个StudentMapper
加上注解@Repository
;
否则后面注入时会报错,原因嘛? 在
StudentMapper.xml
中实现这个函数
<select id="selectAllStudent" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
</select>
-
新建一个StudentService的业务类并实现获取所有学生信息的函数
@Service
public class StudentService{
@Autowired
StudentMapper studentMapper;
public List<Student> GetAllStu(){
return studentMapper.selectAllStudent();
}
}
5.在前端显示所有学生名字
- 新建一个
HomeController
控制类
@Controller
public class HomeController {
@Autowired
StudentService studentService;
@RequestMapping(value = "/")
public String gethome(Model model){
List<Student> allstu = new ArrayList<>();
allstu = studentService.GetAllStu();
model.addAttribute("wgstu",allstu);
return "index";
}
}
-
新建一个index.html文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>mybatis测试</title>
</head>
<body>
<div th:each="astu,astuStat: ${wgstu}">
<div class="letter-content">
<div>
<span th:text="${astu.getUsername()}">我的标题</span>
</div>
</div>
</div>
</body>
</html>
6.在springboot
主入口添加注解,里面值为Mapper
对应的Java
接口类
@MapperScan("com.wglvzyx.mybatisredis.dao")
7.完成启动项目
效果图