本文基于SpringBoot+Mybatis+Mysql5.5完成了一个简单Demo,实现了基本CRUD功能。开发工具为Eclipse。
Eclipse创建Maven工程
"1.0" encoding="UTF-8"?>
"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">
4.0.0</modelVersion>
springboot</groupId>
springboot</artifactId>
0.0.1-SNAPSHOT</version>
springboot</name>
<!-- Spring Boot 启动父依赖 -->
org.springframework.boot</groupId>
spring-boot-starter-parent</artifactId>
2.1.3.RELEASE</version>
</parent>
<!-- Spring Boot web依赖 -->
org.springframework.boot</groupId>
spring-boot-starter-web</artifactId>
</dependency>
org.springframework.boot</groupId>
spring-boot-starter-test</artifactId>
test</scope>
</dependency>
<!-- Spring Boot mybatis依赖 -->
org.mybatis.spring.boot</groupId>
mybatis-spring-boot-starter</artifactId>
2.0.0</version>
</dependency>
<!-- Spring Boot jdbc依赖 -->
org.springframework.boot</groupId>
spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- Spring Boot mysql依赖 -->
mysql</groupId>
mysql-connector-java</artifactId>
runtime</scope>
</dependency>
</dependencies>
</project>
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数据库报错问题
如果Eclipse中resources下创建mapping文件夹显示异常,比如显示为包图标,解决方案如下:
解决eclipse maven工程中src/main/resources目录下创建的文件夹所显示样式不是文件夹,而是"包"图标样式的问题
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;
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 + '\'' +
'}';
}
}
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 "删除失败!";
}
}
}
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;
}
}
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);
}
"1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
"org.spring.springboot.mapper.UserMapper">
"BaseResultMap" type="org.spring.springboot.entity.User">
"id" jdbcType="INTEGER" property="id" />
"userName" jdbcType="VARCHAR" property="userName" />
"passWord" jdbcType="VARCHAR" property="passWord" />
"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,否则报错 -->
<!-- 更新 -->
"updateUserById" parameterType="org.spring.springboot.entity.User">
update user set realName = #{realName} where
<if test="id!= null and id!= ''">
id = #{id}
</if>
</update>
<!-- 新增 -->
"insertUser" parameterType="org.spring.springboot.entity.User">
insert into user(id,userName,passWord,realName) values (#{id},#{userName},#{passWord},#{realName})
</insert>
<!-- 删除 -->
"deleteById" parameterType="org.spring.springboot.entity.User">
delete from user where id = #{id}
</delete>
</mapper>
这里记录一个错误及其解决方案:
Caused by: org.xml.sax.SAXParseException; 必须为元素类型 “update” 声明属性 “resultType”
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);
}
}
注意:项目中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
查询结果如下:
UserController
// 新增
@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()) {
return "插入成功!";
} else {
return "插入失败!";
}
}
UserService
//新增
public boolean insertUser() {
//普通for循环插入
for (int i = 0; i <20; i++) {
User user = new User();
user.setId(i);
user.setUserName("testusername" + i);
user.setPassWord("testpassword"+i);
user.setRealName("testrealname"+i);
userMapper.insertUser(user);
}
//userMapper.insertUser(user);
return true;
}
UserMapper.xml
<insert id="insertUser" parameterType="org.spring.springboot.entity.User">
insert into user(id,userName,passWord,realName) values (#{id},#{userName},#{passWord},#{realName})
insert>
执行http://localhost:8086/testBoot/insertUser
插入结果如下:
UserController同方案一,保持不变
UserMapper
/*
*如果启动类不添加mapper映射,则此处需要添加mapper注解
*/
@Mapper
@Repository
public interface UserMapper {
List<User> list = new ArrayList<>();
//查询
User Sel(int id);
//更新
boolean updateUserById(User user);
//新增
//boolean insertUser(User user);
//新增
boolean insertUser(List<User> user);
//删除
boolean deleteById(int id);
}
UserService更改如下
//新增
public boolean insertUser() {
/*
//普通for循环插入
for (int i = 0; i <20; i++) {
User user = new User();
user.setId(i);
user.setUserName("testusername" + i);
user.setPassWord("testpassword" + i);
user.setRealName("testrealname"+i);
userMapper.insertUser(user);
}
*/
//userMapper.insertUser(user);
List<User> list1 = new ArrayList<>();
for (int i = 0; i <20; i++) {
User user = new User();
user.setId(i);
user.setUserName("*testusername*" + i);
user.setPassWord("*testpassword*"+i);
user.setRealName("*testrealname*"+i);
list.add(user);
}
userMapper.insertUser(list1);
return true;
}
UserMapper.xml
foreach中的collection代表集合名称,比如list1。item代表遍历汇总的别名。
<insert id="insertUser" parameterType="org.spring.springboot.entity.User">
insert into user(id,userName,passWord,realName) values
<foreach collection="list1" item="user" separator=",">
(#{user.id},#{user.userName},#{user.passWord},#{user.realName})
foreach>
insert>
执行http://localhost:8086/testBoot/insertUser
插入结果如下
参考链接如下:
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的使用