SpringBoot 整合 Mybatis 和 Mysql (详细版)
结构如下
1、引入相关依赖
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
2、配置application.yml文件
server:
port: 80
servlet:
context-path:
spring:
# 配置文件选择(dev,pro)
profiles:
active: dev
# 国际化(消息源自动配置,springboot默认找出messages)
messages:
basename: i18n.messages
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/fallenfairy?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: admin
type: com.alibaba.druid.pool.DruidDataSource
mybatis:
# mapper文件
mapper-locations: mapper/*/*Mapper.xml
# 实体类
type-aliases-package: com.fallenfairy.*.pojo
3、启动类添加@MapperScan注解
@SpringBootApplication
@MapperScan("com.fallenfairy.*.dao")
public class FallenfairyApplication {
public static void main(String[] args) {
SpringApplication.run(FallenfairyApplication.class, args);
}
}
6、编写mapper.xml文件
<?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.example.demo.dao.UserDAO"> <!--id对应UserDAO接口方法名--> <!--parameterType对应参数类型--> <!--resultType对应返回值类型--> <!--注意sql语句字段和数据库对应--> <select id="getUserById" parameterType="int" resultType="com.example.demo.pojo.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper>
7、编写controller测试
/** * Copyright (C), 2017-2018, XXX有限公司 * FileName: UserController * Author: 丶Zh1Guo * Date: 2018/11/21 16:51 * Description: user控制器 * History: * <author> <time> <version> <desc> * 作者姓名 * 〈一句话功能简述〉<br> * 〈user控制器〉 * * @author 丶Zh1Guo * @create 2018/11/21 * @since 1.0.0 */ @RestController public class UserController { @Autowired private UserDAO userDAO;
// url: xxx/user?id=1 @RequestMapping("/user") public User getUser(@RequestParam("id") int id){ return userDAO.getUserById(id); } // url: xxx/user/1 @RequestMapping("/user/{id}") public User getUser2(@PathVariable int id){ return userDAO.getUserById(id); } }
8、启动服务测试
测试第一种@RequestParam("id") int id:
测试第二种@PathVariable int id:
若访问报错如下:
mysql运行报The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone
设置数据库时区为东八区即可
设置数据库连接:(增加:&serverTimezone=GMT%2B8)
driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/flexo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8 username: root password: admin
或修改数据时区:
ok