Spring boot Mybatis 整合(完整版)

2021-05-31 19:04

阅读:891

标签:方法   filter   charset   ack   enable   dstat   actor   sub   produce   

个人开源项目
springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页、个人作品、个人博客)
企业级延迟任务方案之RabbitMQ死信队列
更多干货
SpringBoot系列目录

正题
本项目使用的环境:

开发工具:Intellij IDEA 2017.1.3
springboot: 1.5.6
jdk:1.8.0_161
maven:3.3.9
额外功能

PageHelper 分页插件
mybatis generator 自动生成代码插件
步骤:
1.创建一个springboot项目:

2.创建项目的文件结构以及jdk的版本

3.选择项目所需要的依赖


然后点击finish

5.看一下文件的结构:


6.查看一下pom.xml:


xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

com.winter
springboot-mybatis-demo
0.0.1-SNAPSHOT
jar

springboot-mybatis-demo
Demo project for Spring Boot


org.springframework.boot
spring-boot-starter-parent
1.5.6.RELEASE


UTF-8
UTF-8
1.7



org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0


org.springframework.boot
spring-boot-starter-thymeleaf


org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter-test
test


mysql
mysql-connector-java
5.1.35



com.fasterxml.jackson.core
jackson-core


com.fasterxml.jackson.core
jackson-databind


com.fasterxml.jackson.datatype
jackson-datatype-joda


com.fasterxml.jackson.module
jackson-module-parameter-names



com.github.pagehelper
pagehelper-spring-boot-starter
1.1.2



com.alibaba
druid-spring-boot-starter
1.1.0




org.springframework.boot
spring-boot-maven-plugin



org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2

${basedir}/src/main/resources/generator/generatorConfig.xml
true
true




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
7.项目不使用application.properties文件 而使用更加简洁的application.yml文件:
将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,
文件的内容如下:


server:
port: 8080

spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/depot
username: root
password: root
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select ‘x‘
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20

## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
mapper-locations: classpath:mapping/*.xml #注意:一定要对应mapper映射xml文件的所在路径
type-aliases-package: com.winter.model # 注意:对应实体类的路径

#pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
8.创建数据库:

CREATE DATABASE mytest;

CREATE TABLE t_user(
user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(255) NOT NULL ,
password VARCHAR(255) NOT NULL ,
phone VARCHAR(255) NOT NULL
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
1
2
3
4
5
6
7
8
9.使用mybatis generator 自动生成代码:

配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml

br> PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
点击run-Edit Configurations


添加配置


运行
注意!!!同一张表一定不要运行多次,因为mapper的映射文件中会生成多次的代码,导致报错,切记


最后生成的文件以及结构:

 

10. 生成的文件

UserMapper.java

package com.winter.mapper;

import com.winter.model.User;

public interface UserMapper {
int deleteByPrimaryKey(Integer userId);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(Integer userId);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);
//这个方式我自己加的
List selectAllUser();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
User.java

package com.winter.model;

public class User {
private Integer userId;

private String userName;

private String password;

private String phone;

public Integer getUserId() {
return userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
对于sql语句这种黄色的背景,真心是看不下去了(解决方案):


**UserMapper.xml **












user_id, user_name, password, phone





delete from t_user
where user_id = #{userId,jdbcType=INTEGER}


insert into t_user (user_id, user_name, password,
phone)
values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{phone,jdbcType=VARCHAR})


insert into t_user


user_id,


user_name,


password,


phone,




#{userId,jdbcType=INTEGER},


#{userName,jdbcType=VARCHAR},


#{password,jdbcType=VARCHAR},


#{phone,jdbcType=VARCHAR},




update t_user


user_name = #{userName,jdbcType=VARCHAR},


password = #{password,jdbcType=VARCHAR},


phone = #{phone,jdbcType=VARCHAR},


where user_id = #{userId,jdbcType=INTEGER}


update t_user
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR}
where user_id = #{userId,jdbcType=INTEGER}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
11.打开类SpringbootMybatisDemoApplication.java,这个是springboot的启动类。我们需要添加点东西:

package com.winter;

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

@SpringBootApplication
@MapperScan("com.winter.mapper")//将项目中对应的mapper类的路径加进来就可以了
public class SpringbootMybatisDemoApplication {

public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
注意:@MapperScan("com.winter.mapper")这个注解非常的关键,这个对应了项目中mapper(dao)所对应的包路径,很多同学就是这里忘了加导致异常的

12.到这里所有的搭建工作都完成了,接下来就是测试的工作,没使用junit4进行测试:
首先看一下完成之后的文件的结构:


现在controller,service层的代码都写好:

UserController.java

package com.winter.Controller;

import com.winter.model.User;
import com.winter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* Created by Administrator on 2017/8/16.
*/
@Controller
@RequestMapping(value = "/user")
public class UserController {

@Autowired
private UserService userService;

@ResponseBody
@RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
public int addUser(User user){
return userService.addUser(user);
}

@ResponseBody
@RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = {"application/json;charset=UTF-8"})
public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){

return userService.findAllUser(pageNum,pageSize);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
UserService.java

package com.winter.service;

import com.winter.model.User;

import java.util.List;

/**
* Created by Administrator on 2017/8/16.
*/
public interface UserService {

int addUser(User user);

List findAllUser(int pageNum, int pageSize);
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
UserServiceImpl.java

package com.winter.service.impl;

import com.github.pagehelper.PageHelper;
import com.winter.mapper.UserMapper;
import com.winter.model.User;
import com.winter.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* Created by Administrator on 2017/8/16.
*/
@Service(value = "userService")
public class UserServiceImpl implements UserService {

@Autowired
private UserMapper userMapper;//这里会报错,但是并不会影响

@Override
public int addUser(User user) {

return userMapper.insertSelective(user);
}

/*
* 这个方法中用到了我们开头配置依赖的分页插件pagehelper
* 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
* pageNum 开始页数
* pageSize 每页显示的数据条数
* */
@Override
public List findAllUser(int pageNum, int pageSize) {
//将参数传给这个方法就可以实现物理分页了,非常简单。
PageHelper.startPage(pageNum, pageSize);
return userMapper.selectAllUser();
}
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
如果强迫症看不下去那个报错:(解决方法)


测试我使用了idea一个很用心的功能。
可以发http请求的插件:

 


点击左侧的运行按钮就可以发送请求了;
如果返回值正确 说明你已经搭建成功了!!

Spring boot Mybatis 整合(完整版)

标签:方法   filter   charset   ack   enable   dstat   actor   sub   produce   

原文地址:https://www.cnblogs.com/cpjl456/p/14729217.html


评论


亲,登录后才可以留言!