Mybatis是在国内使用是最广泛的,以前都是使用xml进行映射,说实话真心不太好用,维护起来也不太方便。 从mybatis3.0后开始支持 @Mapper注解,极大方便了开发,几乎不在需要任何xml进行配置了。下面重点就讲下Mybatis的相关整合与@Mapper的使用。
首先,配置pom.xml文件,添加以下配置项
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
第二步,在application.yml配置文件中添加以下配置项
spring:
datasource:
platform: mysql
url: jdbc:mysql://localhost/jeealfa_boot?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
initialization-mode: never
schema: classpath:db/schema.sql
# 配置slq打印日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
schema.sql文件内容户名测试要用,可以收到创建数据库,然后运行,如下: 也可以把 initialization-mode值设为always, 首次运行后修改为never.
drop table IF exists `user`;
create table `user`(
`id` int(11) not null auto_increment,
`name` varchar(60) not null default "" comment "姓名",
`age` int(11) not null default 0,
primary key (`id`),
unique key (`name`)
)engine=InnoDB default charset=utf8;
第三步,创建数据model,内容如下
package com.jeealfa.model;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private int age;
}
第四步,创建UserMapper,内容如下
package com.jeealfa.mapper;
import com.jeealfa.model.User;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User queryById(@Param("id") int id);
@Insert("INSERT INTO user(name,age) VALUES(#{name},#{age})")
int add(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int delById(int id);
@Update("UPDATE user SET name=#{name},age=#{age} WHERE id=#{id}")
int updateById(User user);
}
第五步,在Controller中使用
//省略
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/querybyid")
public User queryById(int id){
return userMapper.queryById(id);
}
@RequestMapping("/add")
public String add(User user){
return userMapper.add(user) == 1?"success":"failed";
}
}
第六步,mybatis-plus提供了BaseMapper,提供了一些列通用功能,极大方便了Mapper的开发,使用中可以直接继承此接口。BaseMapper提供的功能有:
package com.baomidou.mybatisplus.core.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
public interface BaseMapper<T> extends Mapper<T> {
int insert(T entity);
int deleteById(Serializable id);
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
int delete(@Param("ew") Wrapper<T> queryWrapper);
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);
int updateById(@Param("et") T entity);
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);
T selectById(Serializable id);
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
T selectOne(@Param("ew") Wrapper<T> queryWrapper);
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);
List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
<E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);
<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}
UserMapper可以改为
@Mapper
public interface UserMapper extends BaseMapper<User>{
}
第7步,整合pageHelper, 在pom.xml里添加
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
<version>1.2.3</version>
</dependency>
在application.yml里新增如下篇日志项:
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
第8步,在控制器中使用分页
@RequestMapping("/user/list")
public Page<User> getMap(@RequestParam(value = "page", defaultValue = "0") int page,
@RequestParam(value = "size", defaultValue = "5") int size){
PageHelper.startPage(page, size, "id desc");
Page<User> list = userMapper.listAll();
System.out.println(list);
return list;
}
注意:PageHelper.startPage执行之后,必须紧跟列表查询方法,不然分页可能会不起作用。
UserMapper中添加listAll接口方法,如下
package com.jeealfa.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.Page;
import com.jeealfa.model.User;
import org.apache.ibatis.annotations.*;
@Mapper
public interface UserMapper2 extends BaseMapper<User> {
@Select("SELECT * FROM user")
Page<User> listAll();
}
可通过postman进行测试。
第9步,自定义sql。 Mybatis提供了@SelectProvider注解来进行自定义sql查询。
见下面事例:
package com.jeealfa.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.Page;
import com.jeealfa.model.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.builder.annotation.ProviderContext;
import org.apache.ibatis.jdbc.SQL;
import java.util.List;
import java.util.Map;
@Mapper
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM user")
Page<User> listAll();
@SelectProvider(type = UserMapper.SelectSql.class, method = "sql")
List<User> queryByPage(Page page, @Param("orderby") String orderby);
class SelectSql{
public String sql(Object object, ProviderContext context){
Map map = (Map) object;
Page page = (Page) map.get("page");
String orderby = (String) map.get("orderby");
return (new SQL()).SELECT("*").FROM("user").
ORDER_BY(orderby).
LIMIT(page.getStartRow()+","+page.getPageSize())
.toString();
}
}
}
自定义sql是灵活的,利用SelectProvider, 甚至可以自己手动写一个BaseMapper。