欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot整合MyBatis實(shí)現(xiàn)CRUD操作項(xiàng)目實(shí)踐

 更新時(shí)間:2024年02月06日 15:18:33   作者:fpl1116  
本文主要介紹了SpringBoot整合MyBatis實(shí)現(xiàn)CRUD操作項(xiàng)目實(shí)踐,如何實(shí)現(xiàn)數(shù)據(jù)庫的CRUD創(chuàng)建、讀取、更新、刪除操作,具有一定的參考價(jià)值,感興趣的可以了解一下

SpringBoot整合MyBatis項(xiàng)目進(jìn)行CRUD操作項(xiàng)目示例

1.1.需求分析

通過使用 SpringBoot+MyBatis整合實(shí)現(xiàn)一個(gè)對(duì)數(shù)據(jù)庫中的 users 表的 CRUD

1.2.創(chuàng)建工程

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 的啟動(dòng)器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Mybatis 啟動(dòng)器 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- mysql 數(shù)據(jù)庫驅(qū)動(dòng) -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!-- druid 數(shù)據(jù)庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
        <!-- 添加 junit 環(huán)境的 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.啟動(dòng)類

@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.數(shù)據(jù)表設(shè)計(jì)

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環(huán)境進(jìn)行整合
 *   	@Contextconfiguartion("classpath:applicationContext.xml")  
 *  junit與SpringBoot整合: 
 *		@RunWith(SpringJUnit4ClassRunner.class):讓junit與spring環(huán)境進(jìn)行整合
 *		@SpringBootTest(classes={App.class}):加載SpringBoot啟動(dòng)類。啟動(dòng)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;

	/**
	 * 頁面跳轉(zhuǎn)
	 */
	@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.測(cè)試

在這里插入圖片描述

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

	/**
	 * 查詢?nèi)坑脩?
	 */
	@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.測(cè)試

在這里插入圖片描述

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>注冊(cè)</title>
</head>
<body>
<center>
	<h3>登錄</h3>
	<hr/>
	<form th:action="@{/user/login}" method="post">
		賬號(hào):<input type="text" name="nam"/><br/>
		密碼:<input type="text" name="pwd"/><br/>
		<input type="submit" value="確定"/><br/>
	</form>
</center>
</body>
</html>

4.6.測(cè)試

在這里插入圖片描述

5.SpringBoot整合日期轉(zhuǎn)換器

5.1.添加日期轉(zhuǎn)換器

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.配置日期轉(zhuǎn)換器

  • 說明

    WebMvcConfigurer配置類其實(shí)是Spring內(nèi)部的一種配置方式,采用JavaBean的形式來代替?zhèn)鹘y(tǒng)的xml配置文件形式針對(duì)框架進(jìn)行個(gè)性化定制,例如:攔截器,類型轉(zhuǎn)化器等等。

  • 代碼示例

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

 到此這篇關(guān)于SpringBoot整合MyBatis實(shí)現(xiàn)CRUD操作項(xiàng)目實(shí)踐的文章就介紹到這了,更多相關(guān)SpringBoot MyBatis CRUD操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Maven deploy配置方法詳解

    Maven deploy配置方法詳解

    這篇文章主要介紹了Maven deploy配置方法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • java中@DateTimeFormat和@JsonFormat注解的使用

    java中@DateTimeFormat和@JsonFormat注解的使用

    本文主要介紹了java中@DateTimeFormat和@JsonFormat注解的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • Java和Rust實(shí)現(xiàn)JSON序列化互轉(zhuǎn)的解決方案詳解

    Java和Rust實(shí)現(xiàn)JSON序列化互轉(zhuǎn)的解決方案詳解

    這篇文章主要為大家詳細(xì)介紹了Java和Rust實(shí)現(xiàn)JSON序列化互轉(zhuǎn)的解決方案,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-03-03
  • @Scheduled fixedDelayString 加載properties配置方式

    @Scheduled fixedDelayString 加載properties配置方式

    這篇文章主要介紹了@Scheduled fixedDelayString 加載properties配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • java DecimalFormat常用方法詳解

    java DecimalFormat常用方法詳解

    這篇文章主要為大家詳細(xì)介紹了java DecimalFormat的常用方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • 解決springboot遇到autowire注入為null的問題

    解決springboot遇到autowire注入為null的問題

    這篇文章主要介紹了解決springboot遇到autowire注入為null的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • Spring如何自定義XML配置擴(kuò)展

    Spring如何自定義XML配置擴(kuò)展

    這篇文章主要介紹了Spring如何自定義XML配置擴(kuò)展,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-12-12
  • 淺談MyBatis 如何執(zhí)行一條 SQL語句

    淺談MyBatis 如何執(zhí)行一條 SQL語句

    Mybatis 是 Java 開發(fā)中比較常用的 ORM 框架。在日常工作中,我們都是直接通過 Spring Boot 自動(dòng)配置,并直接使用,但是卻不知道 Mybatis 是如何執(zhí)行一條 SQL 語句的,下面就一起講解一下
    2021-05-05
  • 用Java驗(yàn)證pdf文件的電子章簽名

    用Java驗(yàn)證pdf文件的電子章簽名

    這篇文章主要介紹了如何用Java驗(yàn)證pdf文件的電子章簽名,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2020-12-12
  • SpringBoot中的CSRF攻擊及預(yù)防方法

    SpringBoot中的CSRF攻擊及預(yù)防方法

    CSRF攻擊是一種常見的網(wǎng)絡(luò)攻擊方式,可以通過欺騙用戶來執(zhí)行惡意操作,在Spring Boot應(yīng)用程序中,我們可以采取多種措施來預(yù)防CSRF攻擊,本文將給大家介紹一下CSRF攻擊以及如何預(yù)防攻擊,需要的朋友可以參考下
    2023-07-07

最新評(píng)論