依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--分页-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.8</version>
</dependency>
配置DataSource
mysql的version高于6要这样配
spring.datasource.url=jdbc:mysql://localhost:3306/yangce?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
创建mapper接口
添加@Repository注解,并在启动类上添加@MapperScan("mapper所在全限定名包名")
声明方法
如果查询语句简单,可直接在方法上使用注解@Select("sql语句")
如果使用*Mapper.xml
- 在resource资源文件夹下创建mapper包,将xml文件放于此处;
- 在application.properties中配置mybatis-mapper-locations=classpath:mapper/*Mapper.xml;
编写SQL
mapper.xml编写时注意namespace与mapper包名一致,select等SQL的id与接口方法一致;
SQL语句中使用接口方法的参数,给参数添加注解@Param("paramName");
参数为自定义类,使用形式为#{person.name},动态SQL的test条件使用时形式为test="person.name != null";
自定义TypeHandler
pojo字段为自定义类型,比如pojo字段为SexEnum类型,表字段为tinyint类型,需要自定义TypeHandler
- 自定义SexEnumTypeHandler extends BaseTypeHandler,实现四个方法,一个set,三个get
preparedStatement.setObject(i, ((SexEnum)o).getCode()); //从enum中得到数值类型的字段赋给表字段
return SexEnum.getByCode(resultSet.getInt(columnName)); //由表的数值类型字段转换为enum
return SexEnum.getByCode(resultSet.getInt(columnIndex)); //由表的数值类型字段转换为enum
return SexEnum.getByCode(callableStatement.getInt(columnIndex)); //由表的数值类型字段转换为enum
- 在SexEnumTypeHandler上添加注解@MapperJdbcTypes(JdbcType.TINYINT),@MapperTypes(SexEnum.class)
- 在application.properties中配置mybatis.type-handlers-package: typehandler所在全限定包名
分页
配置PageInterceptor,启动类中添加代码
@Bean
public PageInterceptor pageInterceptor(){
Properties properties = new Properties();
properties.setProperty("helperDialect", "mysql");
PageInterceptor pageInterceptor = new PageInterceptor();
pageInterceptor.setProperties(properties);
return pageInterceptor;
}
通过mapper使用
//只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询(Select)方法会被分页
PageHelper.startPage(pageNum, pageSize);
List<Person> persons = personMapper.getAll();