Spring Boot入门七:集成MyBatis

一.创建项目

项目名称为 “springboot_mybatis_demo”,创建过程中勾选 “Web”,“MyBatis”,“MySQL”,第一次创建Maven需要下载依赖包(耐心等待)

二.实现

2.1创建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
package com.woniu.bean;


public class User {
private long id;
private String name;
private int age;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}


}

2.2创建UserMapper接口
创建接口UserMapper,并添加@Mapper注解

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.woniu.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.woniu.bean.User;

@Mapper
public interface UserMaper {

@Select("select * from user where age = #{age}")
User Select(int age);
}

2.3创建controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.woniu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.woniu.bean.User;
import com.woniu.mapper.UserMaper;

@RestController
@RequestMapping("/web")
public class WebController {
@Autowired
private UserMaper mapper;


@RequestMapping("/index",method=RequestMethod.GET)
public User selectAge(@RequestParam("age") int age){

return mapper.Select(age);
}
}

2.4设置application.properties

1
2
3
4
5
# mysql
spring.datasource.url=jdbc:mysql://localhost/spring_boot_demo?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2.5MySQL中创建对应数据库和表
数据库名:”spring_boot_demo”,表名:”user”

三.测试

运行项目测试结果如下:

springboot_mybatis_demo资源地址:点击打开链接

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×