bean
@Data
public class Student {
private Integer id;
private String name;
private Integer age;
private String className;
}
controller
@Controller
public class StudentController {
@Autowired
StudentService studentService;
@GetMapping("getall")
public String getall(Model model){
List<Student> list = studentService.getAll();
model.addAttribute("info", list);
return "mycrud";
}
}
service
@Service
public class StudentService {
@Autowired
StudentMapper studentMapper;
public List<Student> getAll() {
return studentMapper.findAll();
}
}
mapper
@Mapper
public interface StudentMapper {
List<Student> findAll();
}
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.myself.wykpage.mapper.StudentMapper">
<resultMap type="com.myself.wykpage.bean.Student" id="studentMap">
<id property="id" column="id" />
<result property="name" column="name" />
<result property="age" column="age" />
<result property="className" column="class_name" />
</resultMap>
<select id="findAll" resultMap="studentMap">
select * from student
</select>
</mapper>
properties配置内容
spring.datasource.username=root
spring.datasource.password=1234
spring.datasource.url=jdbc:mysql://localhost:3306/students
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:xml/*.xml
pom.xml配置内容(配置在plugin标签中)
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
前端页面
<table cellpadding="5" cellspacing="0" border="1">
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>className</th>
</tr>
<tr th:each="students:${info}">
<td th:text="${students.id}"></td>
<td th:text="${students.name}"></td>
<td th:text="${students.age }"></td>
<td th:text="${students.className}"></td>
</tr>
<tr>
完成!!