本文共 2424 字,大约阅读时间需要 8 分钟。
一、注解方式
1.pom.xml配置
mysql
mysql-connector-java
8.0.21
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.1.1
2.配置文件application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/school?characterEncoding=UTF-8&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3.实体类Student
package com.example.demo_zhang.pojo;
public class Student {
private long stuId;
private String name;
private long sex;
public long getStuId() {
return stuId;
}
public void setStuId(long stuId) {
this.stuId = stuId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSex() {
return sex;
}
public void setSex(long sex) {
this.sex = sex;
}
}
4.StudentMapper
package com.example.demo_zhang.mapper;
import com.example.demo_zhang.pojo.Student;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component
public interface StudentMapper {
@Select("select * from student")
List findAll();
}
5.StudentController
package com.example.demo_zhang.web;
import com.example.demo_zhang.mapper.StudentMapper;
import com.example.demo_zhang.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class StudentController {
@Autowired
StudentMapper studentMapper;
@RequestMapping("/listStudent")
public String listStudent(Model m)throws Exception{
List stu = studentMapper.findAll();
m.addAttribute("stu", stu);
return "listStudent";
}
}
6.listStudent.jsp
pageEncoding="UTF-8"%>
stuId | name | sex |
${s.stuId} | ${s.name} | ${s.sex} |
7.运行http://127.0.0.1:8080/listStudent
二、xml配置mybatis
1.xml配置需要去掉上面StudentMapper中的@select注解,同时在mapper包下新增Student.xml。
/p>
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
select * from student
2.修改application.properties
#mybatis目录
mybatis.mapper-locations=classpath:com/example/demo_zhang/mapper/*.xml
mybatis.type-aliases-package=com.example.demo_zhang.pojo
3.在pom.xml下增加如下内容。具体原因不清楚,在一个帖子下,说把mapper下的xml放在resouces下可以不加。
src/main/java
**/*.xml
5.小节,如果没有第三步,则会出现org.apache.ibatis.binding.BindingException错误
转载地址:http://xlggp.baihongyu.com/