DAY45–SpringBoot–整合Mybatis
SpringBoot集成Mybatis
- (1) 准备数据库创建student表
create database springboot_test;
create table student(
sno int primary key auto_increment,
sname varchar(20),
sage int
ssex varchar(2)
)
public class Student {
private String sno;
private String sname;
private int sage;
private String ssex;
- (2)添加启动器依赖;(自动添加 使用springboot init 勾选)
- (3) 配置Mybatis:实体类别名包,日志,映射文件等
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/wang?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
mybatis:
type-aliases-package: com.lxy.demo2.domain
mapper-locations: classpath:com.lxy.demo2.dao/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
@SpringBootApplication
@MapperScan("com.lxy.demo2.dao")
public class Demo2MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Demo2MybatisApplication.class, args);
}
}
- (4) 编写Mapper
public interface StudentDao {
List<Student> findAll();
}
- (5) 配置Mapper映射文件
<?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.lxy.demo2.dao.StudentDao">
<select id="findAll" resultType="student">
select * from student
</select>
</mapper>
- (6) 测试
@SpringBootTest
@MapperScan("com.lxy.demo2.dao")
class Demo2MybatisApplicationTests {
@Autowired
private StudentDao dao;
@Test
void contextLoads() {
List<Student> all = dao.findAll();
System.out.println(all);
}
}
Mysql驱动8的问题
java.sql.SQLException: The server time zone value
(1)com.mysql.cj.jdbc.Driver
(2)jdbcURL
jdbc:mysql://127.0.0.1:3306/test01?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8