本文共 1883 字,大约阅读时间需要 6 分钟。
项目名称为 “springboot_mybatis_demo”,创建过程中勾选 “Web”,“MyBatis”,“MySQL”,第一次创建Maven需要下载依赖包(耐心等待)
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 + "]"; } }
创建接口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);}
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") public User selectAge(int age){ return mapper.Select(age); }}
# 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
数据库名:"spring_boot_demo",表名:"user"
运行项目测试结果如下:
Spring Boot 六:日志输出配置log4j2
Spring Boot 五:使用properties配置文件实现多环境配置
Spring Boot 四:配置文件详解properties
Spring Boot 二:创建第一个web工程 hello world
原文出处:Java架构师之路
原文链接: 转载请与作者联系,同时请务必标明文章原始出处和原文链接及本声明。