logo头像
书院的十三先生

Web应用全栈之旅-Spring篇(二)集成mybatis

一、pom文件

引入mybatis

1
2
3
4
5
6
7
8
9
10
      <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

二、yml配置

添加数据库配置和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
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
database.url=127.0.0.1:3306
spring.datasource.url=jdbc:mysql://${database.url}/demodb?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
spring.datasource.username=root
spring.datasource.password=admin123

mybatis.mapper-locations=classpath:mapper/*.xml
```
## <b>三、DAO</b>
定义DAO接口,添加@Mapper注解:
```java
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import com.javashizhan.demo.mybatis.domain.User;

@Mapper
public interface UserDAO {

User findUserByName(@Param(value = "name") String name) throws Exception;

void createUser(@Param(value = "user") User user) throws Exception;

int deleteUserByName(@Param(value = "name") String name) throws Exception;
}
```

## <b>四、mybatis数据库脚本配置文件</b>
脚本配置文件User.xml:
```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.javashizhan.demo.mybatis.dao.UserDAO">

<!-- id值和DAO方法名保持一致,返回类型和DAO返回对象一致,字段别名和User字段名一致 -->
<select id="findUserByName" resultType="com.javashizhan.demo.mybatis.domain.User">
select
NAME name,
AGE age,
GENDER gender
from USER where name = #{name}
</select>

<insert id="createUser">
insert USER(
NAME,
AGE,
GENDER
) values(
#{user.name},
#{user.age},
#{user.gender}
)
</insert>

<insert id="deleteUserByName">
delete from USER where name = #{name}
</insert>
</mapper>
```
将此文件放到resources目录的子目录mapper下,和yml配置文件中的路径一致。
<img src="/img/a009/1_1.jpg">

## <b>五、Service中调用DAO</b>
```java
@Service
public class UserService {

@Autowired
private UserDAO userDAO;

public User findUserByName(@Param(value = "name") String name) throws Exception {
return userDAO.findUserByName(name);
}

public void createUser(@Param(value = "user") User user) throws Exception {
userDAO.createUser(user);
}

public int deleteUserByName(@Param(value = "name") String name) throws Exception {
return userDAO.deleteUserByName(name);
}
}

以上为spring集成mybatis的所有步骤,完整实例代码扫码加入微信公众号并回复:webfullstack,获取仓库地址。

end.


站点: http://javashizhan.com/


微信公众号:


加入知识星球,参与讨论,更多实战代码分享!
https://t.zsxq.com/RNzfi2j