(一)创建maven工程添加依赖
<!--SpringBoot整合Mybatis的启动器-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--web模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
(二)创建数据库表
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`money` double(10,2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1005 DEFAULT CHARSET=utf8
(三)创建数据模型
public class Account implements Serializable {
private Integer id;
private String name;
private double money;
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;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
(四)创建接口和mapper配置文件
@Mapper
public interface AccountMapper {
Account findById(Integer id);
}
配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.offcn.AccountMapper">
<!-- Account findById(Integer id);-->
<select id="findById" resultType="com.offcn.pojo.Account">
select * from acccont where id=#{id}
</select>
</mapper>
(五)配置application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
# 配置mybatis规则
mybatis:
#config-location: classpath:mybatis/mybatis-config.xml #全局配置文件位置
mapper-locations: classpath:mybatis/mapper/*.xml #sql映射文件位置
type-aliases-package: com.offcn.pojo #配置了实体的别名
configuration:
map-underscore-to-camel-case: true #开启 驼峰式命名法 不写全局,局配置文件的配置都放在configuration对象当中
#在控制台打印sql语句
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
(六)创建业务层接口和实现类
业务层接口:
public interface AccountService {
Account findByIdService(Integer id);
}
实现类:
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public Account findByIdService(Integer id) {
return accountMapper.findById(id);
}
}
(七)创建控制器controller
@Controller
@RequestMapping("account")
public class AccountController {
@Autowired
private AccountService accountService;
@GetMapping("findById")
@ResponseBody
public Account findById(Integer id){
return accountService.findByIdService(id);
}
}
(八)启动服务测试结果
访问地址:http://localhost:8080/account/findById?id=1001
测试结果: