SpringBoot整合MyBatis實現增刪改查案例完整版
阿新 • • 發佈:2020-09-14
1.Spring Boot
Spring Boot是一個簡化Spring開發的框架。用來監護spring應用開發,約定大於配置,去繁就簡,just run 就能建立一個獨立的,產品級的應用。
我們在使用Spring Boot時只需要配置相應的Spring Boot就可以用所有的Spring元件,簡單的說,spring boot就是整合了很多優秀的框架,不用我們自己手動的去寫一堆xml配置然後進行配置。從本質上來說,Spring Boot就是Spring,它做了那些沒有它你也會去做的Spring Bean配置。
閒話少說,上圖文:
2.開始
- 新建一個專案
- 選擇Spring Initializr專案
- 建立專案的檔案結構以及jdk的版本,本次以demo為例
- 選擇專案所需要的依賴
- 修改專案名,finish完成,本次選擇為修改
來看一眼pom檔案
<?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 https://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.2.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <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>2.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
- 修改配置檔案本,文不使用application.properties檔案 而使用更加簡潔的application.yml檔案。
修改為application.yml
內容:
server: port: 8080 spring: datasource: username: root password: root url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapping/*Mapper.xml type-aliases-package: com.example.entity.demo logging: level: com: example: mapper : debug
建立表:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
目錄結構:
UserController.java
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
/**
* @author yn2333
* @Date 2020/03/03
*/
@RestController
@RequestMapping("/test")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/selectUserByid", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
@ResponseBody
public String GetUser(User user){
return userService.Sel(user).toString();
}
@RequestMapping(value = "/add", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public String Add(User user){
return userService.Add(user);
}
@RequestMapping(value = "/update", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public String Update(User user){
return userService.Update(user);
}
@RequestMapping(value = "/delete", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
public String Delete(User user){
return userService.Delete(user);
}
}
User.java
package com.example.demo.entity;
/**
* @author yn2333
* @Date 2020/03/03
*/
public class User {
private Integer id;
private String username;
private String password;
private String address;
public User(Integer id, String username, String password, String address) {
this.id = id;
this.username = username;
this.password = password;
this.address = address;
}
public Integer getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getAddress() {
return address;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", address='" + address + '\'' +
'}';
}
}
UserMapper.java
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
/**
* @author yn2333
* @Date 2020/03/03
*/
@Repository
public interface UserMapper {
User Sel(@Param("user")User user);
int Add(@Param("user")User user);
int Update(@Param("user")User user);
int Delete(@Param("user")User user);
}
UserService.java
package com.example.demo.service;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author yn2333
* @Date 2020/03/03
*/
@Service
public class UserService {
@Autowired
UserMapper userMapper;
public User Sel(User user) {
return userMapper.Sel(user);
}
public String Add(User user) {
int a = userMapper.Add(user);
if (a == 1) {
return "新增成功";
} else {
return "新增失敗";
}
}
public String Update(User user) {
int a = userMapper.Update(user);
if (a == 1) {
return "修改成功";
} else {
return "修改失敗";
}
}
public String Delete(User user) {
int a = userMapper.Delete(user);
if (a == 1) {
return "刪除成功";
} else {
return "刪除失敗";
}
}
}
DemoApplication.java
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author yn2333
* @Date 2020/03/03
*/
@MapperScan("com.example.demo.mapper") //掃描的mapper
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
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.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.entity.User">
<result column="id" jdbcType="INTEGER" property="id"/>
<result column="userName" jdbcType="VARCHAR" property="username"/>
<result column="passWord" jdbcType="VARCHAR" property="password"/>
<result column="realName" jdbcType="VARCHAR" property="address"/>
</resultMap>
<select id="Sel" resultType="com.example.demo.entity.User">
select * from user where 1=1
<if test="user.id != null">
AND id = #{user.id}
</if>
</select>
<insert id="Add" parameterType="com.example.demo.entity.User">
INSERT INTO user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="user.username != null">
username,
</if>
<if test="user.password != null">
password,
</if>
<if test="user.address != null">
address,
</if>
</trim>
<trim prefix="VALUES (" suffix=")" suffixOverrides=",">
<if test="user.username != null">
#{user.username,jdbcType=VARCHAR},
</if>
<if test="user.password != null">
#{user.password,jdbcType=VARCHAR},
</if>
<if test="user.address != null">
#{user.address,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="Update" parameterType="com.example.demo.entity.User">
UPDATE user
<set>
<if test="user.username != null">
username = #{user.username},
</if>
<if test="user.password != null">
password = #{user.password},
</if>
<if test="user.address != null">
address = #{user.address},
</if>
</set>
WHERE
id=#{user.id}
</update>
<delete id="Delete" parameterType="com.example.demo.entity.User">
DELETE FROM user WHERE id = #{user.id}
</delete>
</mapper>
3.測試
- 啟動
- 新增:
127.0.0.1:8080/test/add?username=無極&password=123456&address=上海市
- 查詢:
127.0.0.1:8080/test/selectUserByid?id=1
- 修改
127.0.0.1:8080/test/update?id=1&username=碼雲&password=654321&address=北京
- 刪除
127.0.0.1:8080/test/delete?id=1
增、刪、改、查基本測試已經通過,Navicat重新整理 之後就能看到效果。
原始碼以及sql檔案已打包
下載方式一:https://download.csdn.net/download/weixin_44395707/12223942
下載方式二:
掃下方二維碼關注公眾號回覆:code001即可獲取