使用通用的Mapper,不需要再写**Mapper.xml,多数情况下,连接口都不需要自己定义了,可以很大程度上提高开发效率,很多时候只需要关注业务逻辑。
建议使用Mapper4.0,较之之前的版本,修改了一些Bug,配置更完善。Mybatis建议升级到3.4.0+,以免低版本与Mapper4.0有不适配的地方。
springboot使用Mapper很简单,首先在pom中引入依赖的包(最新版本可以到Maven Repository查看):
tk.mybatis
mapper-spring-boot-starter
2.0.2
然后在配置文件中设置响应的配置信息(详细的配置项请阅读手册:Mapper Configs),以.yml文件为例:
mapper:
identity: MYSQL # 取主键的方式
before: true # 主键递增
not-empty: true # 按主键插入或更新时,是否判断字符串 != ''
style: camelhumpandlowercase # 实体类与表中字段的映射方式:驼峰转带下划线的小写格式
wrap-keyword: '{0}' # 自动配置关键字,配置后不需要使用 @Column 指定别名
safe-delete: true # 删除时必须设置查询条件
safe-update: true # 更新时必须设置查询条件
use-java-type: true # 是否映射Java基本数据类型
mappers: tk.mybatis.mapper.common.Mapper
抽象对象模型(定义实体类),比如定义一个简单的用户信息
public class User {
@Id
private Long id;
private String name; // 姓名
@NotNull
private String mobile; // 手机号
private String email; // 邮箱
private String IDNo; // 身份证号
@Version
private int version;
// setter、getter 方法省略
}
@Id 定义该字段为主键,根据上面的配置信息,id主键自增,@Version表明version字段用来实现乐观锁机制。如果要实现联合主键,则只需要在相应字段上加注解@Id即可。
在项目的启动类加上Mapper的扫描注解 @MapperScan:
@SpringBootApplication
@MapperScan(basePackages = "com.**.service")
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
继承、扩展通用Mapper接口,实现自己特定的查询接口
public interface UserMapper extends Mapper {
@Select("select * from user where id = #{uid}")
User findById(Long uid);
@Insert("insert into user (name, mobile) values (#{name}, #{mobile})")
void add(User user);
@Select("select * from user where id = #{uid}" )
User find(@Param("uid") Long uid);
}
单元测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
@Autowired
private UserDao userDao;
@Test
public void testUserMapper(){
// 自定义的按Id查询方法
User user = userDao.find(1L);
// Mapper 通用的按主键查询方法,不需要自己重新定义
User user2 = userDao.selectByPrimaryKey(1L);
}
}
以上两种查询方法可以得到相同的查询结果。