SpringBoot学习3之数据库集成mybatis

SpringBoot学习3之数据库集成mybatis

 

 

微信公众号" IT程序猿进化史", 共同学习进化~

https://darylliu.github.io/archives/6c6770f1.html

 

作为一个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

 

@Mapper

public interface UserMapper {

@Select("SELECT * FROM user WHERE user.user_id = #{userId}")

@Results({

@Result(column = "user_id", property = "id"),

@Result(column = "user_name", property = "name")

})

User getById(@Param("userId") long houseId);

}

创建Service

 

1

2

3

4

5

6

7

8

9

 

@Service

public class UserService {

@Autowired

private UserMapper userMapper;

public User getById(long id) {

return userMapper.getById(id);

}

}

Controller中调用

 

1

2

3

4

5

6

7

 

@Autowired

private UserService userService;

@RequestMapping("/{id}")

public String getById(@PathVariable("id") int id, Model model) {

model.addAttribute("user", userService.getById(id));

return "show";

}

查询成功!

 

 

详情请访问我的博客:https://darylliu.github.io/archives/6c6770f1.html开链接

 

微信公众号" IT程序猿进化史", 共同学习进化~

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值