版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ln152315/article/details/71545716
SpringBoot学习3之数据库集成mybatis
微信公众号" IT程序猿进化史", 共同学习进化~
作为一个Web框架,必然要与数据库打交道,这里介绍了如何将SpringBoot与mybatis进行集成的方法
添加相关依赖
pom.xml如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<!-- 使用数据源 -->
<dependency>
<groupId>com.alibaba
</groupId>
<artifactId>druid
</artifactId>
<version>1.0.14
</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql
</groupId>
<artifactId>mysql-connector-java
</artifactId>
<scope>runtime
</scope>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot
</groupId>
<artifactId>mybatis-spring-boot-starter
</artifactId>
<version>1.1.1
</version>
</dependency>
|
在配置文件application-dev.yml中配置
1
2
3
4
5
6
|
spring:
datasource:
url: jdbc:mysql://10.31.85.33:3306/School?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNull
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
|
创建实体类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
class User {
private Integer id;
private String name;
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;
}
}
|
创建Mapper接口
1
2
3
4
5
6
7
8
9
|
public
interface UserMapper {
"SELECT * FROM user WHERE user.user_id = #{userId}")
(
"user_id", property =
"id"),
(column =
"user_name", property =
"name")
(column =
})
User getById(@Param("userId") long houseId);
}
|
创建Service
1
2
3
4
5
6
7
8
9
|
public
class UserService {
private UserMapper userMapper;
public User getById(long id) {
return userMapper.getById(id);
}
}
|
Controller中调用
1
2
3
4
5
6
7
|
private UserService userService;
"/{id}")
(
public String getById(@PathVariable("id") int id, Model model) {
model.addAttribute(
"user", userService.getById(id));
return
"show";
}
|
查询成功!
详情请访问我的博客:点击打 http://www.darylliu.top/2017/04/24/99/开链接