|
1 | | -## Spring Boot 集成 Mybatis 和 pagehelper 分页插件 |
| 1 | +## Spring Boot 集成 Mybatis 和 PageHelper 分页插件 |
2 | 2 |
|
3 | | -### 项目依赖 |
| 3 | +MyBatis 是一款优秀的持久层框架,它对 JDBC 的操作数据库的过程进行封装,支持定制化 SQL、存储过程以及高级映射,避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJO(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。 |
4 | 4 |
|
5 | | -```java |
6 | | -<!--mybatis依赖--> |
| 5 | +通俗地讲,MyBatis 就是我们使用 Java 程序操作数据库时的一种工具,可以简化我们使用 JDBC 时的很多操作,而且还简化了数据库记录与 POJO 之间的映射方式。 |
| 6 | + |
| 7 | +### 添加相关依赖 |
| 8 | + |
| 9 | +**MyBatis 依赖** |
| 10 | + |
| 11 | +```xml |
7 | 12 | <dependency> |
8 | 13 | <groupId>org.mybatis.spring.boot</groupId> |
9 | 14 | <artifactId>mybatis-spring-boot-starter</artifactId> |
10 | 15 | <version>1.3.1</version> |
11 | 16 | </dependency> |
| 17 | +``` |
12 | 18 |
|
13 | | -<!--mapper依赖--> |
14 | | -<dependency> |
15 | | - <groupId>tk.mybatis</groupId> |
16 | | - <artifactId>mapper-spring-boot-starter</artifactId> |
17 | | - <version>2.0.0</version> |
18 | | -</dependency> |
| 19 | +**PageHelper 分页插件依赖** |
19 | 20 |
|
20 | | -<!--pagehelper分页插件--> |
| 21 | +```xml |
21 | 22 | <dependency> |
22 | 23 | <groupId>com.github.pagehelper</groupId> |
23 | 24 | <artifactId>pagehelper-spring-boot-starter</artifactId> |
24 | 25 | <version>1.2.3</version> |
25 | 26 | </dependency> |
26 | 27 | ``` |
27 | 28 |
|
28 | | -### 集成 MyBatis Generator |
| 29 | +### 配置数据源信息 |
29 | 30 |
|
30 | | -Mybatis Geneator 详解: |
31 | | -><http://blog.csdn.net/isea533/article/details/42102297> |
32 | | -##### 1. 在项目的根目录下添加 generatorConfig.xml 文件,并引入逆向工程核心依赖 |
33 | | - - generatorConfig.xml文件信息 |
34 | | -```java |
35 | | -<?xml version="1.0" encoding="UTF-8"?> |
36 | | -<!DOCTYPE generatorConfiguration |
37 | | - PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" |
38 | | - "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> |
39 | | - |
40 | | -<generatorConfiguration> |
41 | | - <context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat"> |
42 | | - <property name="beginningDelimiter" value="`"/> |
43 | | - <property name="endingDelimiter" value="`"/> |
44 | | - |
45 | | - <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> |
46 | | - <property name="mappers" value="com.example.mybatis.utils.MyMapper"/> |
47 | | - </plugin> |
48 | | - |
49 | | - <!-- 数据库连接地址--> |
50 | | - <jdbcConnection driverClass="com.mysql.jdbc.Driver" |
51 | | - connectionURL="jdbc:mysql://localhost:3306/game" |
52 | | - userId="root" |
53 | | - password="root"> |
54 | | - </jdbcConnection> |
55 | | - |
56 | | - <!-- 对于生成的pojo所在包 --> |
57 | | - <javaModelGenerator targetPackage="com.example.mybatis.entity" targetProject="src/main/java"/> |
58 | | - |
59 | | -<!-- 对于生成的mapper所在目录 --> |
60 | | - <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> |
61 | | - |
62 | | -<!-- 配置mapper对应的java映射 --> |
63 | | - <javaClientGenerator targetPackage="com.example.mybatis.mapper" targetProject="src/main/java" |
64 | | - type="XMLMAPPER"/> |
65 | | - |
66 | | - <!--数据库中的表名--> |
67 | | -<table tableName="student"></table> |
68 | | - |
69 | | - </context> |
70 | | -</generatorConfiguration> |
71 | | -``` |
72 | | - - 在pom.xml中添加逆向工程核心依赖 |
73 | | -```java |
74 | | -<!--逆向工程核心依赖--> |
75 | | -<dependency> |
76 | | - <groupId>org.mybatis.generator</groupId> |
77 | | - <artifactId>mybatis-generator-core</artifactId> |
78 | | - <version>1.3.2</version> |
79 | | - <scope>compile</scope> |
80 | | - <optional>true</optional> |
81 | | -</dependency> |
82 | | -``` |
83 | | -### 根据配置的 generatorConfig.xml 生成通用Mapper |
84 | | -- 启动以下程序,生成相关Mapper |
85 | | -```java |
86 | | -public class GeneratorDisplay { |
87 | | - |
88 | | - public void generator() throws Exception { |
89 | | - List<String> warnings = new ArrayList<>(); |
90 | | - |
91 | | - // 创建逆向工程配置文件 |
92 | | - File configFile = new File("generatorConfig.xml"); |
93 | | - // 配置解析器 |
94 | | - ConfigurationParser parser = new ConfigurationParser(warnings); |
95 | | - // 解析配置文件 |
96 | | - Configuration configuration = parser.parseConfiguration(configFile); |
97 | | - DefaultShellCallback shellCallback = new DefaultShellCallback(true); |
98 | | - MyBatisGenerator generator = new MyBatisGenerator(configuration, shellCallback, warnings); |
99 | | - generator.generate(null); |
100 | | - |
101 | | - |
102 | | - } |
103 | | - |
104 | | - public static void main(String[] args) { |
105 | | - try { |
106 | | - new GeneratorDisplay().generator(); |
107 | | - } catch (Exception e) { |
108 | | - e.printStackTrace(); |
109 | | - } |
110 | | - } |
111 | | -} |
112 | | -``` |
113 | | -### application.properties 配置 |
114 | | -```java |
115 | | -# 数据库配置 |
116 | | -spring.datasource.url=jdbc:mysql://localhost:3306/game |
| 31 | +```properties |
| 32 | +# 数据源配置 |
| 33 | +spring.datasource.url=jdbc:mysql://localhost:3306/game?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 |
117 | 34 | spring.datasource.username=root |
118 | 35 | spring.datasource.password=root |
119 | 36 | spring.datasource.driver-class-name=com.mysql.jdbc.Driver |
120 | 37 |
|
121 | | -# 配置数据源,使用阿里巴巴的druid数据库连接池 |
| 38 | +# 配置数据源,使用阿里巴巴的 druid 数据库连接池 |
122 | 39 | spring.datasource.druid.initial-size=1 |
123 | 40 | spring.datasource.druid.min-idle=1 |
124 | 41 | spring.datasource.druid.max-active=20 |
125 | 42 | spring.datasource.druid.test-on-borrow=true |
126 | 43 | spring.datasource.druid.stat-view-servlet.allow=true |
| 44 | +``` |
| 45 | + |
| 46 | +### 配置 MyBatis 与 PageHelper 信息 |
127 | 47 |
|
128 | | -# 通用 Mapper 配置 |
129 | | -mapper.mappers=com.example.mybatis.utils.MyMapper |
130 | | -mapper.not-empty=false |
131 | | -mapper.identity=MYSQL |
| 48 | +```properties |
| 49 | +# mybatis 配置 |
| 50 | +mybatis.config-location=classpath:mybatis/mybatis-config.xml |
| 51 | +mybatis.mapper-locations=classpath:mybatis/mapper/*.xml |
| 52 | +mybatis.type-aliases-package=com.example.mybatis.entity |
132 | 53 |
|
133 | | -# pagehelper分页 |
| 54 | +# pagehelper 分页 |
134 | 55 | pagehelper.helperDialect=mysql |
135 | 56 | pagehelper.reasonable=true |
136 | 57 | pagehelper.supportMethodsArguments=true |
137 | 58 | pagehelper.params=count=countSql |
138 | | - |
139 | | -# mybatis 配置 |
140 | | -mybatis.type-aliases-package=com.example.mybatis.entity |
141 | | -mybatis.mapper-locations=classpath:mapper/*.xml |
142 | 59 | ``` |
143 | | -### 使用@MapperScan注解指定扫描的Mapper |
144 | | -**注意**:这里要导入 `tk.mybatis.spring.annotation.*` 下的`MapperScan`,不要导入`org.mybatis.spring.annotation.*` 下的,否则会报错。 |
| 60 | + |
| 61 | +### 创建 Mapper 类与对应的 XML 文件 |
| 62 | + |
| 63 | +Mapper 类是一个接口,它的实现类不是一个 JAVA 类,而是一个与之对应的 XML 文件。Mapper 类中声明的方法对应 XML 文件中的一段 SQL 语句 。 |
| 64 | + |
| 65 | +**Mapper 类** |
| 66 | + |
145 | 67 | ```java |
146 | | -@SpringBootApplication |
147 | | -@MapperScan(basePackages = "com.example.mybatis.mapper") |
148 | | -public class DruidApplication { |
| 68 | +public interface StudentMapper { |
| 69 | + |
| 70 | + Student selectById(Integer id); |
| 71 | + |
| 72 | + List<Student> selectAll(); |
| 73 | + |
| 74 | + void updateStudent(Student student); |
| 75 | + |
| 76 | + void insertStudent(Student student); |
| 77 | + |
| 78 | + void deleteStudent(Integer id); |
149 | 79 |
|
150 | | -public static void main(String[] args) { |
151 | | -SpringApplication.run(DruidApplication.class, args); |
152 | | -} |
153 | 80 | } |
154 | 81 | ``` |
155 | 82 |
|
156 | | -### 自定义Mapper |
157 | | -- 自定义配置mapper.xml文件,手写sql语句 |
158 | | -```java |
| 83 | +**XML 文件** |
| 84 | + |
| 85 | +```xml |
159 | 86 | <?xml version="1.0" encoding="UTF-8"?> |
160 | 87 | <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> |
161 | 88 | <mapper namespace="com.example.mybatis.mapper.StudentMapper"> |
162 | 89 | <resultMap id="BaseResultMap" type="com.example.mybatis.entity.Student"> |
163 | | - <!--WARNING - @mbg.generated--> |
164 | | - <result column="id" jdbcType="INTEGER" property="id"/> |
165 | | - <result column="name" jdbcType="VARCHAR" property="name"/> |
166 | | - <result column="chinese" jdbcType="REAL" property="chinese"/> |
167 | | - <result column="english" jdbcType="REAL" property="english"/> |
168 | | - <result column="math" jdbcType="REAL" property="math"/> |
169 | | - <result column="gender" jdbcType="CHAR" property="gender"/> |
| 90 | + <result column="id" property="id" javaType="java.lang.Integer"/> |
| 91 | + <result column="name" property="name" javaType="java.lang.String"/> |
| 92 | + <result column="age" property="age" javaType="java.lang.Integer"/> |
| 93 | + <result column="gender" property="gender" javaType="com.example.mybatis.constant.GenderEnum"/> |
170 | 94 | </resultMap> |
171 | | - <!--根据id查询--> |
172 | | - <select id="queryById" resultMap="BaseResultMap" parameterType="java.lang.Integer"> |
173 | | - SELECT name,math,gender FROM student WHERE id = #{id,jdbcType=INTEGER} |
| 95 | + |
| 96 | + <sql id="BaseColumnList" > |
| 97 | + id, name, age, gender |
| 98 | + </sql> |
| 99 | + |
| 100 | + <select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer"> |
| 101 | + SELECT |
| 102 | + <include refid="BaseColumnList"/> |
| 103 | + FROM student |
| 104 | + WHERE id = #{id} |
174 | 105 | </select> |
175 | 106 |
|
176 | | - <!-- 查询所有记录--> |
177 | 107 | <select id="selectAll" resultMap="BaseResultMap"> |
178 | | - SELECT * FROM student |
| 108 | + SELECT |
| 109 | + <include refid="BaseColumnList"/> |
| 110 | + FROM student |
179 | 111 | </select> |
| 112 | + |
| 113 | + <insert id="insertStudent"> |
| 114 | + INSERT INTO student ( |
| 115 | + name, |
| 116 | + age, |
| 117 | + gender |
| 118 | + ) VALUES ( |
| 119 | + #{name}, |
| 120 | + #{age}, |
| 121 | + #{gender} |
| 122 | + ) |
| 123 | + </insert> |
| 124 | + |
| 125 | + <update id="updateStudent"> |
| 126 | + UPDATE student |
| 127 | + SET |
| 128 | + <if test="name != null || name != ''">name = #{name},</if> |
| 129 | + <if test="age != null">age = #{age},</if> |
| 130 | + <if test="gender != null">gender = #{gender}</if> |
| 131 | + WHERE id = #{id} |
| 132 | + </update> |
| 133 | + |
| 134 | + <delete id="deleteStudent"> |
| 135 | + DELETE FROM student WHERE id = #{id} |
| 136 | + </delete> |
| 137 | + |
180 | 138 | </mapper> |
181 | 139 | ``` |
182 | | -- 创建mapper类,要与mapper配置文件中的namespace的名字对应 |
183 | | -```java |
184 | 140 |
|
185 | | -/** |
186 | | - * 自定义mapper |
187 | | - * 注意:方法名(queryById)要与StudentMappeCustom.xml文件中的id对应 |
188 | | - * @author kevin |
189 | | - **/ |
190 | | -public interface StudentMapperCustom { |
191 | | - |
192 | | - /** |
193 | | - * 根据id查询记录 |
194 | | - * @param id |
195 | | - * @return |
196 | | - */ |
197 | | - Student queryById(Integer id); |
198 | | - |
199 | | - /** |
200 | | - * 查询所有记录 |
201 | | - * @return |
202 | | - */ |
203 | | - List<Student> selectAll(); |
204 | | -} |
205 | | -``` |
| 141 | +其中 namespace 指定了该 XML 文件对应的 Mapper 类。resultMap 的标签,定义的是我们 SQL 查询的字段与实体类之间的映射关系。 |
| 142 | + |
| 143 | +### 参考 |
| 144 | + |
| 145 | +MyBatis 中文官网:[http://www.mybatis.cn/](http://www.mybatis.cn/) |
206 | 146 |
|
| 147 | +PageHelper 官网:[https://pagehelper.github.io/](https://pagehelper.github.io/) |
207 | 148 |
|
208 | 149 |
|
0 commit comments