一.创建项目
项目名称为 “springboot_mybatis_demo”,创建过程中勾选 “Web”,“MyBatis”,“MySQL”,第一次创建Maven需要下载依赖包(耐心等待)
二.实现
2.1创建User类
1 package com.woniu.bean; 2 3 4 public class User { 5 private long id; 6 private String name; 7 private int age; 8 public long getId() { 9 return id; 10 } 11 public void setId(long id) { 12 this.id = id; 13 } 14 public String getName() { 15 return name; 16 } 17 public void setName(String name) { 18 this.name = name; 19 } 20 public int getAge() { 21 return age; 22 } 23 public void setAge(int age) { 24 this.age = age; 25 } 26 @Override 27 public String toString() { 28 return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; 29 } 30 31 32 }
2.2创建UserMapper接口
创建接口UserMapper,并添加@Mapper注解
1 package com.woniu.mapper; 2 3 import org.apache.ibatis.annotations.Mapper; 4 import org.apache.ibatis.annotations.Select; 5 6 import com.woniu.bean.User; 7 8 @Mapper 9 public interface UserMaper { 10 11 @Select("select * from user where age = #{age}") 12 User Select(int age); 13 }
2.3创建controller
1 package com.woniu.controller; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RestController; 6 7 import com.woniu.bean.User; 8 import com.woniu.mapper.UserMaper; 9 10 @RestController 11 @RequestMapping("/web") 12 public class WebController { 13 @Autowired 14 private UserMaper mapper; 15 16 17 @RequestMapping("/index") 18 public User selectAge(int age){ 19 20 return mapper.Select(age); 21 } 22 }
2.4设置application.properties
1 # mysql 2 spring.datasource.url=jdbc:mysql://localhost/spring_boot_demo?useUnicode=true&characterEncoding=utf-8 3 spring.datasource.username=root 4 spring.datasource.password=123456 5 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
2.5MySQL中创建对应数据库和表
数据库名:"spring_boot_demo",表名:"user"
三.测试
运行项目测试结果如下: