一、环境准备
在使用XML来实现的数据库操作的时候,我们的依赖下载与前面的使用注解时的依赖是一样的。
在配置文件yml格式,也需要添加上跟使用注解时的配置。还要多加上mybatis. mapper-locations: classpath:mapper/**Mapper.xml
二、简单启动
我们先安装一个插件MybatisX,可以帮我们更简单实现xml文件与接口之间的跳转。
mapper接口:
xml文件:
- \ 标签:需要指定 namespace 属性,表⽰命名空间,值为 UserMapperXML 接⼝的全限定名,包括全包名.类名。
- \
- id :是和 Interface (接⼝)中定义的⽅法名称⼀样的,表⽰对接⼝的具体实现⽅法。
- resultType :是返回的数据类型,也就是我们定义的实体类.
测试:
- 结果:
三、增< insert id = >
使用标签< Insert >来写入数据,直接使⽤UserInfo对象的属性名来获取参数。
测试函数:
- 测试结果:
四、返回主键
还是使用< insert >标签来写入数据,只不过设置useGeneratedKeys 和keyProperty属性 。
- useGeneratedKeys:这会令 MyBatis 使⽤ JDBC 的 getGeneratedKeys ⽅法来取出由数据库内部⽣成的主键(⽐如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的⾃动递增字段),默认值:false.
- keyProperty:指定能够唯⼀识别对象的属性,MyBatis 会使⽤ getGeneratedKeys 的返回值或 insert 语句的 selectKey ⼦元素设置它的值,默认值:未设置(unset)
测试方法:
- 结果:
五、删<delete id = >
使用< delete >标签,加上删除的SQL语句即可。
测试方法:
- 结果:
六、改<update id = >
修改数据直接使用< update >注解,加上修改SQL语句即可。
测试方法:
- 结果:
七、查< select id = resultType = >
查询我们只需要使用
- 标签即可。 但是我们也会遇见像前面注解的时候因为字段名和变量名不同而导致映射错误。解决方式与前面也相似。
- 使用起别名的查询语句,将数据库不同字段名取别名为属性名。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.springmybatisdemo.mapper.UserMapperXML"> <select id="selectAll" resultType="com.example.springmybatisdemo.model.UserInfo"> select username , password, age, gender, phone, delete_flag as deleteFlag , create_time as createTime, update_time as updateTime from user_info </select> </mapper>
- 使用配置文件将数据库字段中使用下划线的蛇形命名转换为小驼峰命名。
mybatis.configuration.map-underscore-to-camel-case: true
mybatis: configuration: map-underscore-to-camel-case: true #配置驼峰⾃动转换
- 使用标签result和resultMap。在resultMap标签中放入result标签数组,result标签的column属性对应数据库字段,property属性对应类属性名。当其他查询语句需要使用相同的映射时,这需要在select标签的resultMap属性写上resultMap标签的id属性即可。
<resultMap id="UserMap" type="com.example.springmybatisdemo.model.UserInfo"> <result column="delete_flag" property="deleteFlag"></result> <result column="create_time" property="createTime"></result> <result column="update_time" property="updateTime"></result> </resultMap> <select id="selectAll" resultType="com.example.springmybatisdemo.model.UserInfo" resultMap="UserMap"> select * from user_info </select>