SpringBoot (11) ---- SpringBoot combined with mybatis to add, delete, modify and check

We can use SpringBoot to combine SpringBoot and mybatis to realize the operation of adding, deleting, and modifying the database.

Next, give an example:

The first step is to first create a database test, and create a table tb_user, insert a few pieces of data into tb_user.

create database test;
-- ----------------------------
-- Table structure for tb_user
-- ----------------------------
use test;
DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', 'laowang', '112233');
INSERT INTO `tb_user` VALUES ('2', 'laoli', '123456');

The second step is to build our springboot project, the project structure is as follows,

 

From the project structure, we can see the project file we need to build, springboot startup class DemoApplication.java, control layer class UserController.java, entity class User.java, DAO layer UserMapper.java interface file, Service layer UserService.java , UserMapper.xml mapping file in the mapping folder, static resource file success.html and our SpringBoot application.yml configuration file, Maven configuration file pom.xml.

The third step is to build the pom.xml file, the content of the file is as follows:

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>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.15</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

Here the core introduces jars related to mybatis and mysql databases

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>8.0.15</version>
</dependency> 

The fourth step is to configure the application.yml database file

server:
  port: 8080

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.example.entity

#showSql
logging:
  level:
    com:
      example:
        mapper : debug

The fifth step is to build the contents of the controller, service, Dao, and Data layers

UserController.java

package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author:zk
 * @Date: 2020/4/20 0026
 * @Time: 14:42
 */

@RestController
@RequestMapping("/testBoot")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("getUser/{id}")
    public String GetUser(@PathVariable int id){
    	return userService.Sel(id).toString();
    }
    
    @RequestMapping("findAll")
    public String findAll(){
    	return userService.SelAll().toString();
    }
    
    @RequestMapping("insert/id={id}&username={username}&password={password}")
    public String insert(User user){
        userService.insert(user);
        return "success";
    }
    
    @RequestMapping("delete/id={id}")
    public String delete(User user){
        userService.delete(user);
        return "success";
    }
    
    @RequestMapping("update/id={id}&username={username}&password={password}")
    public String update(User user){
        userService.update(user);
        return "success";
    }
}

User.java

package com.example.entity;

/**
 * @Author:zk
 * @Date: 2020/4/20 0026
 * @Time: 14:42
 */
public class User {
    private Integer id;
    private String username;
    private String password;
   

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
    
    
}

UserMapper.java

package com.example.mapper;

import com.example.entity.User;

import java.util.List;

import org.springframework.stereotype.Repository;

/**
 * @Author:zk
 * @Date: 2020/4/20 0026
 * @Time: 14:42
 */
@Repository
public interface UserMapper {

    User Sel(int id);

	List<User> SelAll();

	int insert(User user);

	int deleteById(User user);

	int updateById(User user);
}

UserMapper.xml

<?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.example.mapper.UserMapper">

	<resultMap id="BaseResultMap" type="com.example.entity.User">
		<result column="id" jdbcType="INTEGER" property="id" />
		<result column="userName" jdbcType="VARCHAR" property="userName" />
		<result column="passWord" jdbcType="VARCHAR" property="passWord" />
	</resultMap>

	<select id="Sel" resultType="com.example.entity.User">
		select * from tb_user where id = #{id}
	</select>

	<select id="SelAll" resultType="com.example.entity.User">
		select * from tb_user
	</select>

	<insert id="insert" parameterType="com.example.entity.User">
		INSERT INTO tb_user
		(
		id,username,password
		)
		VALUES (
		#{id},
		#{username, jdbcType=VARCHAR},
		#{password, jdbcType=VARCHAR}
		)
	</insert>

	<delete id="deleteById">
		Delete from tb_user
		where id=#{id}
	</delete>
	<update id="updateById" parameterType="com.example.entity.User">
		Update tb_user
		SET
		id = #{id},
		username = #{username},
		password = #{password}
		where id = #{id}
	</update>
</mapper>

UserService.java

package com.example.service;

import com.example.entity.User;
import com.example.mapper.UserMapper;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:zk
 * @Date: 2020/4/20 0026
 * @Time: 14:42
 */
@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    public User Sel(int id){
        return userMapper.Sel(id);
    }
	public List<User> SelAll() {
		// TODO Auto-generated method stub
		return userMapper.SelAll();
	}
	public int insert(User user) {
		// TODO Auto-generated method stub
		return userMapper.insert(user);
	}
	public int delete(User user) {
		// TODO Auto-generated method stub
		return userMapper.deleteById(user);
	}
	public int update(User user) {
		// TODO Auto-generated method stub
		return userMapper.updateById(user);
	}
}

Build success.html static resource file

success.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
success
</body>
</html>

The last step, set the startup class

DemoApplication.java

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.example.mapper") //扫描的mapper
@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
}

Then we start the program:

Test increase operation:

 

 

Test the delete operation:

 

 

 

 

 The data just added was deleted

Test modification operation:

 

 

 

 You can see that the data with id = 2 has been modified

Test query operation:

First check all data

 

Check data based on id

At this point our add, delete, modify and check operations are complete.

 Source address: https://github.com/SeulLeo/myspringboot_013

Guess you like

Origin www.cnblogs.com/longlyseul/p/12735743.html