Spring Boot系列教程十:Spring boot集成MyBatis

来源:互联网 发布:魔盒淘宝客 编辑:程序博客网 时间:2024/05/20 07:58

一.创建项目

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

二.实现

2.1创建User类

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;}@Overridepublic String toString() {return "User [id=" + id + ", name=" + name + ", age=" + age + "]";}}

2.2创建UserMapper接口

      创建接口UserMapper,并添加@Mapper注解
package com.woniu.mapper;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Select;import com.woniu.bean.User;@Mapperpublic interface UserMaper {@Select("select * from user where age = #{age}")User Select(int age);}

2.3创建controller

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 {@Autowiredprivate UserMaper mapper;@RequestMapping("/index")public User selectAge(int age){return mapper.Select(age);}}

2.4设置application.properties

# mysqlspring.datasource.url=jdbc:mysql://localhost/spring_boot_demo?useUnicode=true&characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2.5MySQL中创建对应数据库和表

      数据库名:"spring_boot_demo",表名:"user"



三.测试

运行项目测试结果如下:



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

spring boot讨论群:611262656,一键加群:点击加群

更多技术文章请关注微信公众号“Java架构师之路”:




2 0
原创粉丝点击