通过使用 SpringBoot+MyBatis整合实现一个对数据库中的 users 表的 CRUD
04_springboot_mybatis
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.3.2.RELEASEversion>
parent>
<groupId>com.bygroupId>
<artifactId>04_springboot_mybatisartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<java.version>1.8java.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>2.0.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.38version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.0.9version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>3.0version>
dependency>
dependencies>
project>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.username=root
spring.datasource.password=1111
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
mybatis.type-aliases-package=com.by.pojo
logging.level.com.by.mapper=DEBUG
@SpringBootApplication
@MapperScan("com.by.mapper") // @MapperScan 用户扫描MyBatis的Mapper接口
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nam` varchar(255) DEFAULT NULL,
`sex` int(11) DEFAULT NULL,
`pwd` varchar(255) DEFAULT NULL,
`birth` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
public class User {
private Integer id;
private String nam;
private String pwd;
private Integer sex;
private Date birth;
}
public interface UserMapper {
public void insertUser(User user);
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.mapper.UserMapper">
<insert id="insertUser" parameterType="user">
insert into user(nam,pwd,sex,birth) values(#{nam},#{pwd},#{sex},#{birth})
insert>
mapper>
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void addUser(User user) {
this.userMapper.insertUser(user);
}
}
/**
* main方法:
* ApplicationContext ac=new
* ClassPathXmlApplicationContext("classpath:applicationContext.xml");
* junit与spring整合:
* @RunWith(SpringJUnit4ClassRunner.class):让junit与spring环境进行整合
* @Contextconfiguartion("classpath:applicationContext.xml")
* junit与SpringBoot整合:
* @RunWith(SpringJUnit4ClassRunner.class):让junit与spring环境进行整合
* @SpringBootTest(classes={App.class}):加载SpringBoot启动类。启动springBoot
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes={App.class})
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testAddUser(){
User user = new User();
user.setId(1);
user.setNam("二狗");
user.setPwd("111");
user.setSex(1);
user.setBirth(new Date());
this.userService.addUser(user);
}
}
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 页面跳转
*/
@RequestMapping("/{page}")
public String showPage(@PathVariable String page) {
return page;
}
/**
* 添加用户
*/
@RequestMapping("/addUser")
public String addUser(User user) {
this.userService.addUser(user);
return "ok";
}
}
add.html
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加用户title>
head>
<body>
<h3>新增用户h3>
<hr/>
<form th:action="@{/user/addUser}" method="post">
姓名:<input type="text" name="nam"/><br/>
密码:<input type="text" name="pwd"/><br/>
性别:<input type="radio" name="sex" value="1"/>女
<input type="radio" name="sex" value="0"/>男<br/>
生日:<input type="text" name="birth"/><br/>
<input type="submit" value="确定"/><br/>
form>
body>
html>
public List<User> listUser();
<select id="listUser" resultType="user">
select * from user
select>
@Override
public List<User> listUser() {
return userMapper.listUser();
}
/**
* 查询全部用户
*/
@RequestMapping("/listUser")
public String listUser(Model model) {
List<User> list = this.userService.listUser();
model.addAttribute("list", list);
return "list";
}
list.html
DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首页title>
<style type="text/css">
table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto}
table, th, td {border: 1px solid darkslategray;padding: 10px}
style>
head>
<body>
<div style="text-align: center">
<span style="color: darkslategray; font-size: 30px">欢迎光临!span>
<hr/>
<table class="list">
<tr>
<th>idth>
<th>姓名th>
<th>密码th>
<th>性别th>
<th>生日th>
tr>
<tr th:each="user : ${list}">
<td th:text="${user.id}">td>
<td th:text="${user.nam}">td>
<td th:text="${user.pwd}">td>
<td th:text="${user.sex==1}?'男':'女'">td>
<td th:text="${#dates.format(user.birth,'yyyy-MM-dd')}">td>
tr>
table>
div>
body>
html>
public Users login(User user);
<select id="login" parameterType="User" resultType="User">
select * from user where nam=#{nam} and pwd=#{pwd}
select>
@Override
public Users login(User user) {
return userMapper.login(user);
}
@RequestMapping("/login")
public String login(Model model, User user, HttpSession session) {
User loginUser = usersService.login(user);
if(user!=null){
session.setAttribute("loginUser", loginUser);
return "redirect:/user/listUser";
}
return "login";
}
添加PageController
@Controller
public class PageController {
@RequestMapping("/")
public String showLogin(){
return "login";
}
}
login.html
<html>
<head>
<meta charset="UTF-8">
<title>注册title>
head>
<body>
<center>
<h3>登录h3>
<hr/>
<form th:action="@{/user/login}" method="post">
账号:<input type="text" name="nam"/><br/>
密码:<input type="text" name="pwd"/><br/>
<input type="submit" value="确定"/><br/>
form>
center>
body>
html>
import java.text.ParseException;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
import org.apache.commons.lang3.time.DateUtils;
public class DateConverter implements Converter<String, Date>{
@Override
public Date convert(String str) {
String[] patterns = new String[]{
"yyyy-MM-dd","yyyy-MM-dd hh:mm:ss","yyyy/MM/dd","yyyy/MM/dd hh:mm:ss",
"MM-dd-yyyy","dd-MM-yyyy"};
try {
Date date = DateUtils.parseDate(str, patterns);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
说明
WebMvcConfigurer配置类其实是Spring
内部的一种配置方式,采用JavaBean
的形式来代替传统的xml
配置文件形式针对框架进行个性化定制,例如:拦截器,类型转化器等等。
代码示例
import com.by.converter.DateConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class MyConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
}
package com.by.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.by.pojo.Users;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler)throws Exception {
Users user = (Users) request.getSession().getAttribute("user");
if(user!=null){
return true;
}
response.sendRedirect("/");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler,ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex)throws Exception {
}
}
修改MyConfig
//
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/emp/**");
}