MyBatis简介
MyBatis是一款持久层框架,用于简化jdbc的开发,减少了平时开发时的繁琐流程。
MyBatis本是 Apache的⼀个开源项⽬iBatis,2010年这个项⽬由apache迁移到了google code,并 且改名为MyBatis 。2013年11⽉迁移到Github。
简单来说 MyBatis 是更简单完成程序和数据库交互的框架,也就是更简单的连接、操作和读取数据库⼯具。
创建MyBatis项目
和往常创建SpringBoot项目一样,我们只需要在创建SpringBoot项目时勾选对应的框架就好了。
在这里选择MyBatis Framework和MySQL Driver,然后点击create创建项目。
数据库配置
我们采用yml文件的配置方式来配置数据库连接。
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/mybatis_test?charsetEncoding=utf8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
数据准备
现在数据库中建立对应的库和表,然后插入数据。
再根据SpringMVC三层架构,在model层对userinfo创建对应的实体类。接下来就可以对数据进行操作了。
增删改查
通过使用Mapper注解表示MyBatis中的Mapper接口。程序运⾏时, 框架会⾃动⽣成接⼝的实现类对象(代理对象),并给交Spring的IOC容器管理。使用过程也很简单,添加对应的语句注解,在注解内写入对应的语句就好了。
1.增
通过@Insert注解,实现增加语句。
@Mapper
@Insert("insert into userinfo (username, password, age, gender, phone) values " +
"(\"zhaoliu\",\"zhaoliu\",19,1,\"18700001234\")")
void InsertUserInfo();
2.删
通过@Delete注解,实现删除语句。
@Mapper
public interface UserInfoMapper {
@Delete("delete from userinfo where id = 6")
void delete();
}
3.改
通过@Update注解,实现更改语句。
@Mapper
@Update("update userInfo set username = 'zhangsan' where id = 4 ")
void updateUserInfo();
4.查
通过@Select注解,实现查询语句。
@Mapper
public interface UserInfoMapper {
@Select("select username, password, age, gender, phone from userInfo")
public List<UserInfo> queryAllUser();
}
参数传递
在我们上面是演示案例中,sql语句都是写死的,在实际的项目中我们往往需要根据参数来动态的调整sql语句,这时候我们就可以在方法中添加⼀个参数,将⽅法中的参数,传给SQL语句,使用#{ } 的方式获取方法中的参数。
@Update("update userInfo set username = #{username} where id = #{id} ")
void updateUserInfo(String username,Integer id);
注意方法参数和{ }中参数的一致性。
单元测试
我们可以通过单元测试的方法来观察sql语句的执行结果。
首先需要在yml中配置数据库日志格式。
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
点击alert+insert后生成Test单元测试类。
在下面选择要生成的对应测试方法。
单击左侧运行方法。
在打印日志中看到语句成功执行。
检查数据库,数据也成功地被修改。
字段不匹配以及解决方案
在数据库中我们字段的命名往往采用_下划线分割的方式,而在java中我们变量的命名采用的是小驼峰的方式,这就导致了字段不匹配的问题。我们来看下面一组实例代码。
我们希望查询表中所有用户的所有信息。
@Select("select username, password, age, gender, phone, " +
"delete_flag, carete_time, update_time from userInfo")
List<UserInfo> queryAllUser();
通过单元测试的方法查看结果,可以看到后三个字段为空。对于该问题有如下几种解决方法。
1. 起别名
在SQL语句中,给列名起别名,保持别名和实体类属性名⼀样。
@Select("select username, password, age, gender, phone, " +
"delete_flag as deleteFlag, create_time as createTime, update_time as
updateTime from userInfo")
List<UserInfo> queryAllUser();
2. 结果映射
通过@Result注解建立mysql字段和对应实体类之间的属性关系。
@Select("select username, password, age, gender, phone, " +
"delete_flag, create_time, update_time from userInfo")
@Results({@Result(column = "delete_flag",property = "deleteFlag"),
@Result(column = "create_time",property = "createTime"),
@Result(column = "update_time",property = "updateTime")})
List<UserInfo> queryAllUser();
3. 开启命名转换(推荐)
在YML中添加如下的配置文件,也能正确显示查询结果。而且方便简洁。
mybatis:
configuration:
map-underscore-to-camel-case: true
使用以上三种方法,都能够正确的显示查询结果。