搭建SpringBoot项目
在搭建SpringBoot项目时记得选择JDBC、MySQL驱动、MyBatis框架,也可在pom.xml
中手动添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
配置数据库链接
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/blog_fan?serverTimezone=GMT%2B8&characterEncoding=utf8
username: root
password: 123456
注意:
serverTimezone=GMT%2B8
是必须的,MySQL数据库不指定时区连接或报错characterEncoding=utf8
也是需要指定的,否则带中文的数据无法查询到
配置MyBatis
mybatis:
configuration:
# 链接超时时间
default-statement-timeout: 15
# 开启驼峰命名规则映射(用于数据返回映射到实体类)
map-underscore-to-camel-case: true
# xml路径
mapper-locations: classpath:mapper/*.xml
# 别名
type-aliases-package: com.example.entity
批量注解
每个mapper接口都需要加@Mapper
注解,可以在启动类上加批量注解
@MapperScan("com.fan.mapper")
自增列获取ID主键
注解方式
/**
* 添加分类
*/
@Insert("insert into category(name,sort,type) values(#{name},#{sort},#{type})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
Integer insertCategory(Category category);