开始

介绍

img

快速入门

img

导包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

创建实体类

  • src.main.java.com.cyt.domain/User
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
public class User {
private int id;
private String username;
private String password;

@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}

public int getId() {
return id;
}

public void setId(int 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;
}
}

映射文件

  • src.main.resources.com.cyt.mapper/UserMapper.xml
  • namespace 命名空间
  • id sql取名字
  • resultType 结果集 指定domain里的对象
1
2
3
4
5
6
7
8
9
<?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="userMapper">
<select id="findAll" resultType="com.cyt.domain.User">
select *
from user;
</select>
</mapper>

核心文件

  • src.main.resources/sqlMapConfig.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">


<configuration>
<!--数据源环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--连接信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--jdbc:mysql://mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8-->
<property name="url" value="jdbc:mysql://localhost:3306/cyt_db01?useSSL=false&amp;serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="cyt"/>
</dataSource>
</environment>
</environments>
</configuration>

✨✨核心配置文件

img

environments

  • 一般配死

img

1
2
3
4
5
6
7
8
9
10
11
12
13
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--连接信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--jdbc:mysql://mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8-->
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false&amp;serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="cyt"/>
</dataSource>
</environment>
</environments>

配置

  • JDBC
  • POOLED

img

Mapper

  • 第一种用的多

img

1
2
3
4
5
<mappers>
<!--加载sql映射文件-->
<!-- <mapper resource="com/cyt/mapper/UserMapper.xml"/>-->
<package name="com.cyt.mapper"/>
</mappers>

properties

  • 配置数据源信息

img

typeAliases

  • 自定义别名

img

  • 包扫描别名

    • 扫描pojo下的所有类 别名为小写
1
2
3
4
<!--配置别名-->
<typeAliases>
<package name="com.cyt.pojo"/>
</typeAliases>

img

相关API

SqlSessionFactoryBuilder

  • 工厂函数

img

SqlSession

  • 是否自动提交事务

img

  • 会话方法

img

✨✨接口代理方式

img

✨开发方式

img

流程

img

  1. resource/mybatis-config.xml 总的mybatis配置文件
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
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<!--配置别名-->
<typeAliases>
<package name="com.cyt.pojo"/>
</typeAliases>
<!--
environments: 配置数据库连接环境信息 可以配置多个environment
通过default属性配置不同的environment
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--连接信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--jdbc:mysql://mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8-->
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false&amp;serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="cyt"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql映射文件-->
<!-- <mapper resource="com/cyt/mapper/UserMapper.xml"/>-->
<package name="com.cyt.mapper"/>
</mappers>
</configuration>
  1. UserMapper.xml 每个domain对应的Mapper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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.cyt.mapper.UserMapper">
方法名保持和接口一致
<select id="selectALL" resultType="user"> 配置了别名小写user
select *
from tb_user;
</select>
<select id="selectById" resultType="com.cyt.pojo.User">
select *
from tb_user
where id = #{id};
</select>
</mapper>
  1. com.cyt.pojo(domain).User配置类名
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
public class User {
private Integer id;
private String username;
private String password;
private String gender;
private String addr;

@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", addr='" + addr + '\'' +
'}';
}

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 getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getAddr() {
return addr;
}

public void setAddr(String addr) {
this.addr = addr;
}
}
  1. com.cyt.mapper.UserMapper 定义接口方法

    1. 然后回到第二步写sql
1
2
3
4
5
6
public interface UserMapper {

List<User> selectALL();

User selectById(int id);
}
  1. 测试方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void testSelectALL() throws IOException {
// 1.加载文件 获取工厂函数
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

// 2.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();

/* 3.获取Mapper接口的代理对象*/
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
/* 4.执行方法*/
List<Brand> brands = mapper.selectALL();
System.out.println(brands);
sqlSession.close();
}

✨✨mybatis核心配置文件

动态Sql

概述

img

if

  • 用1 = 1代替sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<select id="findByCondition" parameterType="user" resultType="user">
select *
from mybatis.tb_user where 1 = 1
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
<if test="addr != null">
and addr = #{addr}
</if>
</select>
  • 优雅写法 推荐
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<select id="findByCondition" parameterType="user" resultType="user">
select *
from mybatis.tb_user
<where>
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
<if test="addr != null">
and addr = #{addr}
</if>
</where>
</select>
  • 测试传入user
1
2
3
4
5
User user = new User();
user.setUsername("zhangsan");
user.setPassword("123");
user.setAddr("北京");
user.setId(1);

foreach

  • 原型 : 解决where id in (1, 2, 3)

  • 注册接口

1
List<User> findByIds(List<Integer> ids);
  • collection 接受参数集合
  • open 以什么开始
  • close以什么结束
  • item接收集合内的元素取名id
  • separatorin 后的 括号内以什么为间隔
1
2
3
4
5
6
7
8
<select id="findByIds" resultType="com.cyt.pojo.User">
select * from mybatis.tb_user
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
  • 测试数据
1
2
3
4
// 模拟ids数据
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);

sql抽取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!--sql语句抽取-->
<sql id="selectUser">select * from mybatis.tb_user</sql> 抽取

<select id="findByCondition" parameterType="user" resultType="user">
<include refid="selectUser"/> 注入
<where>
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
<if test="addr != null">
and addr = #{addr}
</if>
</where>
</select>

小结

img

typeHandlers

img

重写方法

  1. handler.DateTypeHandler
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
public class DateTypeHandler extends BaseTypeHandler<Date> {
/*java类型转化为数据库需要的类型*/
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
preparedStatement.setLong(i, time);
}

/*数据库中的类型转为java类型*/
// 1.string 参数要转换的字段名
// 2.ResultSet 查询出的结果集
@Override
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
// 获得结果集中需要的数据(long) 转换为Date
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
}

/*数据库中的类型转为java类型*/
@Override
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
Date date = new Date(aLong);
return date;
}

/*数据库中的类型转为java类型*/
@Override
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
Date date = new Date(aLong);
return date;
}
}
  1. mybatis-config.xml核心配置文件
1
2
3
4
<!--注册类型处理器-->
<typeHandlers>
<package name="com.cyt.handler"/>
</typeHandlers>

plugin

  • 扩展功能
  • 分页功能演示

img

步骤

  1. 导包
1
2
3
4
5
6
7
8
9
10
11
<!--分页解析器-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.5</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>0.9.1</version>
</dependency>
  1. mybatis-config.xml核心配置文件
1
2
3
4
5
6
7
<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!--配置方言为mysql-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
  1. 测试
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 1.加载文件 获取工厂函数
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

// 2.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
/* 3.获取Mapper接口的代理对象*/
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

/*设置分页参数:当前页+每页显示的条数 显示第二页3个数据*/
PageHelper.startPage(2,3);


/* 4.执行方法*/
List<User> users = mapper.selectALL();
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
  1. 其他方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*获得与分页相关的参数:*/
/*
当前页:2
每页显示条数:3
总条数:4
总页数:2
上一页是:1
下一页是:0 尾页
是否是第一页:false
是否最后一页:true
* */
PageInfo<User> pageInfo = new PageInfo<>(users);
System.out.println("当前页:" + pageInfo.getPageNum());
System.out.println("每页显示条数:" + pageInfo.getPageSize());
System.out.println("总条数:" + pageInfo.getTotal());
System.out.println("总页数:" + pageInfo.getPages());
System.out.println("上一页是:" + pageInfo.getPrePage());
System.out.println("下一页是:" + pageInfo.getNextPage());
System.out.println("是否是第一页:" + pageInfo.isIsFirstPage());
System.out.println("是否最后一页:" + pageInfo.isIsLastPage());

小结

img

多表操作

一对一模型

  • 通过订单号查到user号

img

  • OrderMapper.xml
  1. resultMap配置别名 映射关系

    1. 主键用id
    2. 其他用result
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
<resultMap id="orderMap" type="order">
<!--手动指定字段和实体属性映射关系
column: oid sql语句中定义的oid
property: order类中的属性
-->
<id column="oid" property="id"/>
<result column="ordertime" property="ordertime"/>
<result column="total" property="total"/>
1
<!--<result column="uid" property="user.id"/>
<result column="username" property="user.username"/>
<result column="password" property="user.password"/>
<result column="birthday" property="user.birthday"/>-->

2
<!--
property:当前实体(order)中的属性名称
javaType:当前实体中的user 属性名称
-->
<association property="user" javaType="user">
<id column="uid" property="id"/>
<result column="username" property="username"/>
<result column="password" property="password"/>
<result column="birthday" property="birthday"/>
</association>
</resultMap>

<select id="findAll" resultType="com.cyt.pojo.Order">
SELECT *, o.id oid FROM orders o, tb_user u WHERE o.uid = u.id
</select>

一对多模型

img

  • User实体类添加字段
1
2
/*当前用户存在哪些订单*/
private List<Order> orderList;
  • 配置

img

多对多

img

  • User实体类添加字段

img

  • 配置

  • user内部roleList字段配置

    • property user实体类字段名字
    • ofType 对应的实体

img

注解开发

常用注解

img

CRUD

  1. mybatis-config.xml核心配置文件
1
2
3
4
5
6
<mappers>
<!--加载sql映射文件-->
<!--指定接口所在的包-->
<!--<mapper resource="com/cyt/mapper/UserMapper.xml"/>-->
<package name="com.cyt.mapper"/>
</mappers>
  1. com.cyt.mapper.UserMapper接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Insert("insert into mybatis.tb_user values (#{id}, #{username}, #{password}, #{gender}, #{addr}, #{Birthday})")
void save(User user);

@Update("update mybatis.tb_user " +
"set username = #{username}, password = #{password} where id = #{id}")
void update(User user);

@Delete("delete from mybatis.tb_user where id = #{id}")
void delete(int id);

@Select("select * from tb_user where id = #{id}")
User findById(int id);

@Select("select * from mybatis.tb_user")
List<User> findAll();
  1. 测试方法
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
public class MybatisTest2 {
private UserMapper mapper;

@Before
public void before() throws IOException {
// 1.加载文件 获取工厂函数
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(inputStream);

// 2.获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession(true);

/* 3.获取Mapper接口的代理对象*/
mapper = sqlSession.getMapper(UserMapper.class);
}

@Test
public void testSave() {
User user = new User();
user.setUsername("tom");
user.setPassword("123");
user.setPassword("qqqq");

mapper.save(user);
}

@Test
public void testUpdate() {
User user = new User();
user.setId(17);
user.setUsername("lucy");
user.setPassword("123");

mapper.update(user);
}

@Test
public void testDelete() {
mapper.delete(17);
}

@Test
public void testFindByid() {
User byId = mapper.findById(2);
System.out.println(byId);
}

@Test
public void testFindAll(){
List<User> all = mapper.findAll();
for (User user : all) {
System.out.println(user);
}
}
}

复杂查询

img

img

一对一

  1. order实体类添加字段
1
2
// 订单属于哪个用户
private User user;
  1. OderMapper添加接口方法
1
2
3
4
5
6
7
8
9
@Select("SELECT *, o.id AS oid FROM orders o, tb_user u WHERE o.uid = u.id")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "total",property = "total"),
@Result(column = "uid",property = "user.id"),
@Result(column = "username",property = "user.username"),
@Result(column = "password",property = "user.password")
})
List<Order> findAll();
  • 另一种方法
1
2
3
4
5
6
7
8
9
10
11
12
13
@Select("SELECT * FROM orders")
@Results({
@Result(column = "oid",property = "id"),
@Result(column = "total",property = "total"),
@Result(
property = "user", // 要封装的属性名称
column = "uid", // 根据哪个字段查询user表的数据
javaType = User.class, // 要封装的实体类型
// select属性 代表查询那个接口的方法获得数据
one = @One(select = "com.cyt.mapper.UserMapper.findById")
)
})
List<Order> findAll2();
  1. 测试
1
2
3
4
5
6
7
@Test
public void testfindAll() {
List<Order> all = mapper.findAll();
for (Order order : all) {
System.out.println(order);
}
}

一对多

  • 通过用户user查找多个对应的order订单号
  1. user添加字段
1
2
/*当前用户存在哪些订单*/
private List<Order> orderList;
  1. OrderMapper接口 uid查找order
1
2
@Select("select * from orders where uid = #{uid}")
List<Order> findByUid(int uid);
  1. UserMapper接口
1
2
3
4
5
6
7
8
9
10
11
12
13
@Select("select * from tb_user")
@Results({
@Result(id = true, column = "id", property = "id"),
@Result(id = true, column = "username", property = "username"),
@Result(id = true, column = "password", property = "password"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.cyt.mapper.OrderMapper.findByUid")
)
})
List<User> findUserAndOrder();

多对多

img

img

✨✨SSM整合

img

导包

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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.itheima</groupId>
<artifactId>itheima_ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>


<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
<!--spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

<!--servlet和jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>

<!--mybatis相关-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

</dependencies>

<build>
<finalName>itheima_ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.example</groupId>
<artifactId>spring_mvc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>

<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>compile</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>

准备

ssm

  1. domain.Account实体类
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
public class Account {
private Integer id;
private String name;
private Double money;

@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Double getMoney() {
return money;
}

public void setMoney(Double money) {
this.money = money;
}
}
  1. mapper.AccountMapperdao 层接口方法
1
2
3
4
5
6
public interface AccountMapper {

void save(Account account);

List<Account> findAll();
}
  1. service.AccountService业务层接口
1
2
3
4
5
public interface AccountService {
void save(Account account);

List<Account> findAll();
}
  • service.impl.AccountServiceImpl 接口实现

img

1
2
3
4
5
6
7
8
9
10
11
public class AccountServiceImpl implements AccountService {
@Override
public void save(Account account) {

}

@Override
public List<Account> findAll() {
return null;
}
}
  1. controller.AccountController web层
1
2
3
4
5
6
7
8
9
10
public class AccountController {
// 保存
public String save(Account account) {
return null;
}
// 查询
public ModelAndView findAll() {
return null;
}
}

配置

jdbc.properties

1
2
3
4
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=cyt

log4j.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
#

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###

log4j.rootLogger=all, stdout

web.xml

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
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">


<!--spring 监听器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!--springmvc的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!--乱码过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

applicationContex.xml

  • spring配置文件
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
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!--组件扫描 扫描service和mapper-->
<context:component-scan base-package="com.itheima">
<!--排除controller的扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>

<!--加载propeties文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

<!--配置数据源信息-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>

<!--配置sessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--加载mybatis核心文件-->
<property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property>
</bean>

<!--扫描mapper所在的包 为mapper创建实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.mapper"></property>
</bean>


<!--声明式事务控制-->
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!--配置事务增强-->
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>

<!--事务的aop织入-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:advisor>
</aop:config>

</beans>

spring-mvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!--组件扫描 主要扫描controller-->
<context:component-scan base-package="com.cyt.controller"/>
<!--配置mvc注解驱动-->
<mvc:annotation-driven/>
<!--内部资源视图解析器-->
<bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--开放静态资源访问权限-->
<mvc:default-servlet-handler/>
</beans>

xxxMapper.xml

  • com.cyt.mapper.AccountMapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?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.cyt.mapper.AccountMapper">
<insert id="save" parameterType="account">
insert into ssm.account
values (#{id}, #{name}, #{money})
</insert>
<select id="findAll" resultType="com.cyt.domain.Account">
select *
from ssm.account
</select>
</mapper>

mybatis-config.xml

  • 或者叫sqlMapConfig.xml
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
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<!--配置别名-->
<typeAliases>
<package name="com.cyt.pojo"/>
</typeAliases>

<!--注册类型处理器-->
<typeHandlers>
<package name="com.cyt.handler"/>
</typeHandlers>

<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!--配置方言为mysql-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>

<!--
environments: 配置数据库连接环境信息 可以配置多个environment
通过default属性配置不同的environment
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--连接信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--jdbc:mysql://mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8-->
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false&amp;serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="cyt"/>
</dataSource>
</environment>
</environments>

<mappers>
<!--加载sql映射文件-->
<!--指定接口所在的包-->
<!--<mapper resource="com/cyt/mapper/UserMapper.xml"/>-->
<package name="com.cyt.mapper"/>
</mappers>
</configuration>

搭建完毕

img

业务编写

service编写方法

  • AccountService
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
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Override
public void save(Account account) {
try {
InputStream resourceAsStream =
Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 调用mapper方法
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
mapper.save(account);
sqlSession.commit();
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public List<Account> findAll() {
try {
InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
List<Account> all = mapper.findAll();
sqlSession.commit();
sqlSession.close();
return all;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

controller层调用方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Controller
@RequestMapping("/account") /*所属模块*/
public class AccountController {
@Autowired
private AccountService accountService;

// 保存
@RequestMapping("/save")
@ResponseBody /*防止跳转*/
public String save(Account account) {
accountService.save(account);
return "保存成功";
}

// 查询
public ModelAndView findAll() {
List<Account> accountList = accountService.findAll();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("accountList", accountList);
modelAndView.setViewName("accountList"); /*视图资源解析器 对应jsp文件*/
return modelAndView;
}
}

测试

  1. tomcat
1
2
3
4
5
6
7
8
9
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>

Spring整合Mybatis

  • 本质:把session创建的控制器交给spring

img

applicationContext.xml

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
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<!--组件扫描 扫描service和mapper-->
<context:component-scan base-package="com.cyt">
<!--排除controller的扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!--加载jdbc properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!--配置数据源信息-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

<!--配置session 工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--加载mybatis核心文件--> 引入下面
<property name="configLocation" value="classpath:sqlMapConfig-spring.xml"/>
</bean>

<!--代替mapper扫包-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.cyt.mapper"/>
</bean>

<!--声明式事务控制-->
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<!--配置事务增强-->
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>

<!--事务aop织入-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cyt.service.impl.*.*(..))"/>
</aop:config>
</beans>

sqlMapConfig-spring.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

<!--定义别名-->
<typeAliases>
<!--<typeAlias type="com.itheima.domain.Account" alias="account"></typeAlias>-->
<package name="com.cyt.domain"/>
</typeAliases>
</configuration>

service

  • 实现方法 调用sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Service("accountService")
public class AccountServiceImpl implements AccountService {

@Autowired
private AccountMapper accountMapper;

public void save(Account account) {
accountMapper.save(account);
}

public List<Account> findAll() {
return accountMapper.findAll();
}
}

事务控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!--声明式事务控制-->
<!--平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<!--配置事务增强-->
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>

<!--事务aop织入-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.cyt.service.impl.*.*(..))"/>
</aop:config>