SpringBoot+Mybatis+Mysql用法Demo

本文基于SpringBoot+Mybatis+Mysql5.5完成了一个简单Demo,实现了基本CRUD功能。开发工具为Eclipse。
一:利用Eclipse创建一个Maven功能,创建方法为
Eclipse创建Maven工程

二:修改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>springboot</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>

    <!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring Boot web依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
		<dependency>
	    	<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
        <!-- Spring Boot mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- Spring Boot jdbc依赖 -->
        <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<!-- Spring Boot mysql依赖 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
    </dependencies>
</project>

三:创建application.yml和application-dev.yml配置文件
application.yml

spring:
  profiles:
    active: dev

application-dev.yml

server:
  port: 8086
 
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
 
mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: org.spring.springboot.entity
 

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

在项目中配置多套环境的配置方法。
因为现在一个项目有好多环境,开发环境,测试环境,准生产环境,生产环境。每个环境的参数不同,所以我们就可以把每个环境的参数配置到yml文件中,这样在想用哪个环境的时候只需要在主配置文件中将用的配置文件写上就行,如application.yml
在Spring Boot中多环境配置文件名需要满足application-{profile}.yml的格式,其中{profile}对应你的环境标识,比如:
application-dev.yml:开发环境
application-test.yml:测试环境
application-prod.yml:生产环境
至于哪个具体的配置文件会被加载,需要在application.yml文件中通过spring.profiles.active属性来设置,其值对应{profile}值。

注意:这里由于采用mysql5.5数据库,所以驱动写成了com.mysql.cj.jdbc.Driver
,否则会报如下错误:
在这里插入图片描述
解决方案为:解决springboot连接MySQL数据库报错问题

四:创建包controller、entity、mapper、service,以及resources下创建mapping文件夹(用于写sql语句,也可以用注解的方式直接写在mapper文件里)

如果Eclipse中resources下创建mapping文件夹显示异常,比如显示为包图标,解决方案如下:
解决eclipse maven工程中src/main/resources目录下创建的文件夹所显示样式不是文件夹,而是"包"图标样式的问题

1:数据库表User

CREATE TABLE `user` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `userName` varchar(32) NOT NULL,
  `passWord` varchar(50) NOT NULL,
  `realName` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

效果如下
在这里插入图片描述
2:实体类User.java

package org.spring.springboot.entity;

public class User {
    private Integer id;
    private String userName;
    private String passWord;
    private String realName;
 
    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;
    }
 
    public String getRealName() {
        return realName;
    }
 
    public void setRealName(String realName) {
        this.realName = realName;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                ", realName='" + realName + '\'' +
                '}';
    }
}

3:控制层UserController.java

package org.spring.springboot.controller;

import javax.servlet.http.HttpServletRequest;
import org.spring.springboot.entity.User;
import org.spring.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

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

	@Autowired
	private UserService userService;

	// 查询
	@RequestMapping("/getUser/{id}")
	@ResponseBody
	public String GetUser(@PathVariable int id) {
		return userService.Sel(id).toString();
	}

	// 更新
	@RequestMapping("/updateUser")
	@ResponseBody
	public String updateUser(HttpServletRequest request) {
		String realName = request.getParameter("realName");
		int id = Integer.parseInt(request.getParameter("id"));
		User user = new User();
		user.setRealName(realName);
		;
		user.setId(id);
		if (userService.updateUserById(user)) {
			return "更新成功!";
		} else {
			return "更新失败!";
		}
	}

	// 新增
	@RequestMapping("/insertUser")
	@ResponseBody
	public String insertUser(HttpServletRequest request) {
		int id = Integer.parseInt(request.getParameter("id"));
		String userName = request.getParameter("userName");
		String passWord = request.getParameter("passWord");
		String realName = request.getParameter("realName");
		User user = new User();
		user.setId(id);
		user.setUserName(userName);
		user.setPassWord(passWord);
		user.setRealName(realName);
		if (userService.insertUser(user)) {
			return "插入成功!";
		} else {
			return "插入失败!";
		}
	}

	// 删除
	@RequestMapping("/deleteById")
	@ResponseBody
	public String deleteById(int id) {
		if (userService.deleteById(id)) {
			return "删除成功!";
		} else {
			return "删除失败!";
		}
	}

}


4:实现类UserService.java

package org.spring.springboot.service;

import org.spring.springboot.entity.User;
import org.spring.springboot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    
    //查询
    public User Sel(int id){
        return userMapper.Sel(id);
    }
    
    //更新
    public boolean updateUserById(User user) {
    	userMapper.updateUserById(user);
        return true;
    }
    
    //新增
    public boolean insertUser(User user) {
    	userMapper.insertUser(user);
        return true;
    }
    
    //删除
    public boolean deleteById(int id) {
    	userMapper.deleteById(id);
        return true;
    }
        
}

5:业务映射UserMapper.java

package org.spring.springboot.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.spring.springboot.entity.User;
import org.springframework.stereotype.Repository;

/*
 *如果启动类不添加mapper映射,则此处需要添加mapper注解 
*/
@Mapper
@Repository
public interface UserMapper {
    //查询
    User Sel(int id);
    //更新
    boolean updateUserById(User user);
    //新增
    boolean insertUser(User user);
    //删除
    boolean deleteById(int id);
}

6:映射配置文件UserMapping.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="org.spring.springboot.mapper.UserMapper">
 
    <resultMap id="BaseResultMap" type="org.spring.springboot.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="realName" />
    </resultMap>
    <!-- 查询 -->
    <select id="Sel" resultType="org.spring.springboot.entity.User">
        select * from user where id = #{id}
    </select>
    
    <!-- 注意:Mapper.xml 文件中的 update标签,去掉resultType,否则报错  -->
    <!-- 更新 -->
    <update id="updateUserById" parameterType="org.spring.springboot.entity.User">
        update user set realName = #{realName} where id = #{id}
    </update>
    
    <!-- 新增 -->
    <insert id="insertUser" parameterType="org.spring.springboot.entity.User">
        insert into user(id,userName,passWord,realName) values (#{id},#{userName},#{passWord},#{realName}) 
    </insert>
    <!-- 删除 -->
    <delete id="deleteById" parameterType="org.spring.springboot.entity.User">
    	delete from user where id = #{id}
    </delete>
    
 </mapper>

这里记录一个错误及其解决方案:
在这里插入图片描述
Caused by: org.xml.sax.SAXParseException; 必须为元素类型 “update” 声明属性 “resultType”

7:启动类

package org.spring.springboot;

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

/**
 * Spring Boot 应用启动类
 * */
/* UserMapper.java 如果不添加Mapper注解,则此处需要添加MapperScan
@MapperScan("com.example.mapper") 
*/
@SpringBootApplication
public class ApplicationApp {

    public static void main(String[] args) {
        // 程序启动入口
        // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
        SpringApplication.run(ApplicationApp.class,args);
    }
}

8:项目最终框架结构
在这里插入图片描述
注意:项目中org.spring.springboot.web包里面内容与本项目无关,仅仅是aop的练习,可以忽略。
最后启动工程
在这里插入图片描述
完成项目下载地址如下
本文Demo工程代码

(1)浏览器输入查询地址:http://localhost:8080/testBoot/getUser/1
查询结果如下:
在这里插入图片描述
(2)浏览器输入更新地址:http://localhost:8086/testBoot/updateUser?id=2&realName=许三多

查询结果如下:
在这里插入图片描述

(3)浏览器输入新增地址:http://localhost:8086/testBoot/insertUser?id=3&userName=test3&passWord=test3password&realName=许三多3

查询结果如下:
在这里插入图片描述

(4)浏览器输入删除地址:http://localhost:8086/testBoot/deleteById?id=3

查询结果如下:
在这里插入图片描述

参考链接如下:

SpringBoot整合Mybatis完整详细版
SpringBoot之整合Mybatis(增,改,删)
解决eclipse maven工程中src/main/resources目录下创建的文件夹所显示样式不是文件夹,而是"包"图标样式的问题
Java连接MySQL数据库8.0以上版本遇到的坑
运行springboot项目报错:Field userMapper in XX required a bean of type ‘xx’ that could not be found.
Springboot之application.properties的使用

猜你喜欢

转载自blog.csdn.net/jike11231/article/details/107415258
今日推荐