SpringBoot+Mybatis+Mysql用法Demo

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

二:修改pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>


4.0.0

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

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

spring:
profiles:
active: dev
1
2
3
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"?>
<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>

这里记录一个错误及其解决方案:

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

查询结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值