1.添加依赖
-
mybatis-springboot的整合依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.1</version> </dependency>
-
mysql驱动依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency>
-
Druid依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.1</version> </dependency>
2.写controller层方法
@Controller
public class firstController {
@Autowired
private StudentService studentService;
@RequestMapping("/abc/register")
public String first(Student student, Model model){
studentService.addStudent(student);
model.addAttribute("name",student.getName());
model.addAttribute("age",student.getAge());
model.addAttribute("student",student);
return "/page/welcome.jsp"; //物理视图
}
}
3.写service层接口和实现类
加@Service注解
public interface StudentService {
void addStudent(Student student);
}
@Service
public class StudentServiceImp implements StudentService {
@Autowired
private IStudentDao studentDao;
@Override
public void addStudent(Student student) {
studentDao.addStudent(student);
}
}
4.写dao层接口和xml文件
一定记得在接口上定义@Mapper注解
@Mapper
public interface IStudentDao {
void addStudent(Student student);
}
<?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.ssp.dao.IStudentDao">
<insert id="addStudent">
insert into student (name,age) values (#{name},#{age})
</insert>
</mapper>
5.在pom.xml中的build中添加资源路径
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
6.在application.yaml中
-
注册映射文件
-
注册实体类包(起别名)
-
注册数据源
mybatis: #注册映射文件(mapper.xml) mapper-locations: classpath:com\ssp\dao\*.xml #注册实体类包 type-aliases-package: com.ssp.bean #注册数据源 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource #四要素 driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql:///student username: root password: root
7.在index.jsp中运行
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/abc/register" method="post">
姓名:<input type="text" name="name">
年龄:<input type="text" name="age">
<input type="submit" value="注册">
</form>
</body>
</html>