(0)准备数据库创建user表
create database springboot_test;
create table person(
id int primary key auto_increment,
name varchar(20),
age int
)
public class Person {
private int id;
private String name;
private int age;
(1) 添加启动器依赖;(自动添加 使用springboot init…勾选)
(2)配置Mybatis:实体类别名包,日志,映射文件等;
spring:
datasource: # hikari
driver-class-name: com.mysql.cj.jdbc.Driver # mysql 8
username: root
password: 123456
url: jdbc:mysql://localhost:3306/springboot_test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
mybatis:
type-aliases-package: com.hy.demo04mybatis.domain #别名
mapper-locations: classpath:com.hy.demo04mybatis.dao/*.xml #xml文件
#使用注解在启动类上面配置 @MapperScan("com.wzx.demo04mybatis.dao")//存放接口
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #mybatis日志
@SpringBootApplication
@MapperScan("com.hy.demo04mybatis.dao")//存放接口
public class Demo04mybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Demo04mybatisApplication.class, args);
}
}
Spring Boot集成Mybatis测试
(4)编写Mapper
public interface PersonDao {
//全查
List<Person> findAllPersons();
}
(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.hy.demo04mybatis.dao.PersonDao">
<select id="findAllPersons" resultType="person">
select * from person
</select>
</mapper>
(6)测试
@SpringBootTest
class Demo04mybatisApplicationTests {
@Autowired
PersonDao dao;//Alt+Enter修复 disabled inspection
@Test
void test01() {
System.out.println(dao.findAllPersons());
}
}
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