上一篇已经记录了Springboot整合Thymeleaf
一、准备工作
首先准备好表和数据
pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
application.properties
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
spring.datasource.username = root
spring.datasource.password = 密码
新建Student类
public class Student {
private Integer id;
private String sname;
getter setter...
}
二、注解方式
新建mapper接口: StudentMapper 加上注解@Mapper
@Mapper
public interface StudentMapper {
@Select("select * from student")
List<Student> findAll();
}
对应的注解有:@Insert、@Delete、@Update
这里省略service层,直接创建Controller
@Controller
@RequestMapping("/studentManage")
public class StudentController {
@Autowired
StudentMapper studentMapper;
@RequestMapping("/listStudent")
public String toStudentView(Model model){
List<Student> students = studentMapper.findAll();
model.addAttribute("students",students);
return "views/listStudent";
}
}
html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>学生</title>
</head>
<body>
<table>
<thead>
<tr>
<th>id</th>
<th>学生姓名</th>
</tr>
</thead>
<tbody>
<tr th:each="s: ${students}">
<td th:text="${s.id}"></td>
<td th:text="${s.sname}"></td>
</tr>
</tbody>
</table>
</body>
</html>
运行项目:访问http://localhost:8080/studentManage/listStudent
注解方式对一些简单的SQL来说还是很方便的,但是实际项目中肯定会有复杂SQL,而复杂的SQL放注解上简直惨不忍睹,所以下面来说一下XML的方式。
三、XML方式
首先把mapper接口的@Select注解去掉
在StudentMapper同文件夹下新建StudentMapper.xml文件 这里要注意namespace 学到这里应该对MyBatis没有疑惑了
<?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.test.demo.mapper.StudentMapper">
<select id="findAll" resultType="com.test.demo.domain.Student">
select * from student
</select>
</mapper>
注意:此时如果把.xml文件放在mapper的同级包下
<!--解决mapper.xml文件的编译问题,如果不指定,在编译的时候,编译器默认只编译类文件,不编译xml文件-->
<resource>
<!--指定源文件夹位置-->
<directory>src/main/java</directory>
<!--指定源文件夹中的哪些资源要进行编译-->
<includes>
<include>**/*.xml</include>
</includes>
</resource>
如果放在resources目录下,在properties文件中指明从哪里去找xml配置文件
mybatis.mapper-locations=classpath:mapper/*.xml
好了其他不用动,运行项目开始访问: 一样的效果
四、扩展
上文中提到要在mapper接口上添加注解@Mapper 实际项目中mapper接口肯定很多,我们可以在主程序上加上
@MapperScan("com.test.demo.mapper")
也可以指定多个包