原创

Springboot+mybatis整合实例

前段时间整合了一个自动化项目,用到了Springboot+mybatis技术。今天通过一个简单的例子要记录一下。

新建一个Spring Initializr项目

1、创建项目Type,包名以及jdk的版本 

点击finish项目创建完成,来看一下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 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.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</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.2.0</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>
</dependency>
</dependencies>

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

</project>

修改配置文件

本文不使用application.properties文件 而使用更加简洁的application.yml文件。将resource文件夹下原有的application.properties文件删除,创建application.yml配置文件(备注:其实SpringBoot底层会把application.yml文件解析为application.properties),本文创建了两个yml文件(application.yml和application-dev.yml),分别来看一下内容

application.yml

spring:
profiles:
active: dev

application-dev.yml

server:
port: 8080

spring:
datasource:
username: root
password: 123456
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.demo.entity

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}值。

开始创建实体类实现业务流程

创建包controller、entity、mapper、service。resources下创建mapping文件夹,用于写sql语句,也可以用注解的方式直接写在mapper文件里。下面直接贴代码

数据库表结构(之前小项目的表,直接拿来用)

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,

`roles`  varchar(32) DEFAULT NULL,

PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

创建entity文件夹,然后新增User的java类,如下:

package com.example.demo.entity;

public class User {

private Integer id;
private String userName;
private String passWord;
private String realName;
private String roles;

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

public String getRoles(){
return roles;
}

public void setRoles(String roles){
this.roles = roles;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", realName='" + realName + '\'' +
", roles='" + roles + '\'' +
'}';
}

}

UserController类

package com.example.demo.controller;

import com.example.demo.core.response.Result;
import com.example.demo.core.response.ResultGenerator;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

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

@Autowired
private UserService userService;

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

@RequestMapping("getAllUsers")
public List<User> GetListUsers(){
return userService.listUsers();
}

@PostMapping("addUser")
public Result save(@RequestHeader("application/json") @RequestBody User user){
this.userService.addUser(user);
return ResultGenerator.genOkResult("200");
}

}

UserMapper .java

package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.springframework.stereotype.Repository;
import java.util.List;


@Repository
public interface UserMapper {

User selectUser(int id);

List<User> listUsers();

int insert(User user);

}

UserService.java

package com.example.demo.service;

import com.example.demo.entity.User;
import java.util.List;


public interface UserService {

boolean addUser(User user);

User selectUser(int id);

List<User> listUsers();


}

UserServiceImpl.java

package com.example.demo.service.impl;

import com.example.demo.core.service.AbstractService;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

@Resource
private UserMapper userMapper;

@Override
public boolean addUser(User user){
boolean result = false;
try{
userMapper.insert(user);
result = true;
}catch (Exception e){
e.printStackTrace();
}
return result;
}

@Override
public User selectUser(int id){
return userMapper.Sel(id);
}

@Override
public List<User> listUsers(){
return userMapper.listUsers();
}

}

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="realName" />
<result column="roles" jdbcType="VARCHAR" property="roles" />
</resultMap>

<select id="selectUser" resultType="com.example.demo.entity.User">
select * from user where id = #{id}
</select>

<select id="listUsers" resultType="com.example.demo.entity.User">
SELECT r.* from User r ORDER BY r.id
</select>

<insert id="insert" parameterType="com.example.demo.entity.User" >
INSERT INTO user (id, userName, passWord, realName, roles)
VALUES (#{id}, #{userName}, #{passWord}, #{realName}, #{roles});
</insert>


</mapper>

查看项目框架结构

最后,我们看一下启动类DemoApplication.java,并做一下配置:@MapperScan("com.example.demo.mapper") 

接下来,我们启动一下项目并调试请求一下接口:
正文到此结束
本文目录