- 需求
用户的CRUD
- 建表
- 配置pom文件,导入需要的starter
- 在application.yml中配置连接参数
- 编写Customer实体
- 编写Mapper接口类
- 编写sql映射文件
- 编写service接口和实现
- 编写controller类
- 编写页面
- 建表
CREATE TABLE `t_customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`gender` char(1) DEFAULT NULL,
`telephone` varchar(20) DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
- 配置pom,导入需要的starter
<!-- mybatis 相关的坐标 -->
<!--mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
- 项目的目录结构
- 编写Customer实体
package com.glodon.springboothello.domain;
/**
*@author clj
*@create 2019-10-27 15:04
**/
public class Customer{
private Integer id;
private String name;
private String gender;
private String telephone;
private String address;
}
- 编写Mapper接口类
命名:实体名+Mapper
- 编写sql映射文件
Sql映射文件的文件名要与Mapper接口类名一致
编写service接口和实现
public interface CustomerService{
public void save(Customer customer);
public List<Customer>findAll();
public Customer findById(Integer id);
public void delete(Integer id);
}
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService{
//注入mapper接口的对象
@Resource
private CustomerMapper customerMapper;
@Override
public void save(Customer customer){
//判断是否添加还是修改
if(customer.getId!=null){
//修改
customerMapper.update(customer);
else{
//添加
customerMapper.save(customer);
}
}
}
- 编写Controller类
@Controller
@RequestMapper("/customer")
public class CustomerController{
@Resource
private CustomerService customerService;
//跳转到input.html页面
@RequestMapping("/input")
public String input(Model model){
Customer customer=new Customer();
model.addAttribute("cust",customer);
return "input";
}
@RequestMapping("/save")
public String save(Customer customer){
customerService.save(customer);
return "succ";
}
}
- 编写页面
•<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>录入客户信息</title>
</head>
<body>
<form th:action="@{~/customer/save}" method="post">
<input type="hidden" name="id" th:field="${cust.id}"/>
客户姓名:<input type="text" name="name" th:field="${cust.name}"/><br/>
客户性别:<input type="text" name="gender" th:field="${cust.gender}"/><br/>
客户手机:<input type="text" name="telephone" th:field="${cust.telephone}"/><br/>
客户住址:<input type="text" name="address" th:field="${cust.address}"/><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>