SpringBoot整合MyBatis实现CRUD操作项目实践

 更新时间:2024年02月06日 15:18:33   作者:fpl1116  
本文主要介绍了SpringBoot整合MyBatis实现CRUD操作项目实践,如何实现数据库的CRUD创建、读取、更新、删除操作,具有一定的参考价值,感兴趣的可以了解一下

SpringBoot整合MyBatis项目进行CRUD操作项目示例

1.1.需求分析

通过使用 SpringBoot+MyBatis整合实现一个对数据库中的 users 表的 CRUD

1.2.创建工程

04_springboot_mybatis

1.3.pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
    </parent>
    
    <groupId>com.by</groupId>
    <artifactId>04_springboot_mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!-- springBoot 的启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Mybatis 启动器 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- mysql 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!-- druid 数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <!-- 添加 junit 环境的 jar 包 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.0</version>
        </dependency>
    </dependencies>
</project>

1.4.application.properties

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

1.5.启动类

@SpringBootApplication
@MapperScan("com.by.mapper") // @MapperScan 用户扫描MyBatis的Mapper接口
public class App {
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}
}

2.添加用户

2.1.数据表设计

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;

2.2.pojo

public class User {
    private Integer id;

    private String nam;

    private String pwd;
    
    private Integer sex;

    private Date birth;
}

2.3.mapper

public interface UserMapper {
    public void insertUser(User user);
}
<?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.by.mapper.UserMapper">
    <insert id="insertUser" parameterType="user">
		insert into user(nam,pwd,sex,birth) values(#{nam},#{pwd},#{sex},#{birth})
	</insert>
</mapper>

2.4.service

@Service
@Transactional
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;

	@Override
	public void addUser(User user) {
		this.userMapper.insertUser(user);
	}
}

2.5.junit

/**
 *  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);
	}
}

2.6.controller

@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";
	}
}

2.7.thymeleaf

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>

2.8.测试

在这里插入图片描述

3.查询用户

3.1.mapper

public List<User> listUser();
<select id="listUser" resultType="user">
	select * from user
</select>

3.2.service

	@Override
	public List<User> listUser() {
		return userMapper.listUser();
	}

3.4.controller

	/**
	 * 查询全部用户
	 */
	@RequestMapping("/listUser")
	public String listUser(Model model) {
		List<User> list = this.userService.listUser();
		model.addAttribute("list", list);
		return "list";
	}

3.5.thymeleaf

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>id</th>
            <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>

3.6.测试

在这里插入图片描述

4.用户登录

4.1.mapper

public Users login(User user);
	<select id="login" parameterType="User" resultType="User">
		select * from user where nam=#{nam} and pwd=#{pwd}
	</select>

4.2.service

	@Override
	public Users login(User user) {
		return userMapper.login(user);
	}

4.4.controller

	@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";
	}
}

4.5.thymeleaf

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>

4.6.测试

在这里插入图片描述

5.SpringBoot整合日期转换器

5.1.添加日期转换器

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;
	}

}

5.2.配置日期转换器

  • 说明

    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());
    	}
    	
    }
    

6.SpringBoot整合拦截器

6.1.添加拦截器

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 {
	}

}

6.2.配置拦截器

修改MyConfig

	//<mvc:interceptors>
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/emp/**");
	}

 到此这篇关于SpringBoot整合MyBatis实现CRUD操作项目实践的文章就介绍到这了,更多相关SpringBoot MyBatis CRUD操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java中为什么要实现Serializable序列化

    Java中为什么要实现Serializable序列化

    在Java编程中,Serializable序列化是一个常见的概念,它允许对象在网络上传输或持久化到磁盘上,本文将深入探讨为什么在Java中要实现Serializable序列化,并通过示例代码来解释其重要性
    2023-10-10
  • SpringBoot 使用log4j2的配置过程

    SpringBoot 使用log4j2的配置过程

    这篇文章主要介绍了SpringBoot 使用log4j2的配置,springboot默认是用logback的日志框架的,所以要在pom中配置排除logback。这里需要注意的是,其实不止一处使用了logback,所以要在starter中统一排除,然后引入log4j2,需要的朋友可以参考下
    2022-09-09
  • 基于Java类的加载方式

    基于Java类的加载方式

    这篇文章主要介绍了基于Java类的加载方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • Java中FileWriter类的常用方法说明

    Java中FileWriter类的常用方法说明

    这篇文章主要介绍了Java中FileWriter类的常用方法说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Spring Boot中配置文件application.properties使用

    Spring Boot中配置文件application.properties使用

    这篇文章主要介绍了Spring Boot中配置文件application.properties使用及spring boot读取application.properties文件的方式,需要的朋友参考下吧
    2018-01-01
  • java使用java.io.File类和java.nio.file.Path类对文件重命名

    java使用java.io.File类和java.nio.file.Path类对文件重命名

    这篇文章主要给大家介绍了关于java使用java.io.File类和java.nio.file.Path类对文件重命名的相关资料,本文仅为日常操作记录,方便后期使用查找本地电脑文件太多了,又不想一个一个重命名,改名字什么的很麻烦,需要的朋友可以参考下
    2024-02-02
  • springboot整合消息队列RabbitMQ

    springboot整合消息队列RabbitMQ

    这篇文章主要介绍了springboot整合消息队列RabbitMQ,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-08-08
  • Spring Boot自定义 Starter并推送到远端公服的详细代码

    Spring Boot自定义 Starter并推送到远端公服的详细代码

    这篇文章主要介绍了Spring Boot自定义 Starter并推送到远端公服,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-09-09
  • SpringBoot配置数据库密码加密的方法

    SpringBoot配置数据库密码加密的方法

    由于系统安全的考虑,配置文件中不能出现明文密码的问题,本文就给大家详细介绍下springboot配置数据库密码加密的方法,下面话不多说了,来一起看看详细的介绍吧,需要的朋友可以参考下
    2023-08-08
  • 学习Java内存模型JMM心得

    学习Java内存模型JMM心得

    这篇文章主要介绍了学习Java内存模型JMM的心得以及对其原理做了深入的介绍,有兴趣的朋友学习下吧。
    2017-12-12

最新评论