MyBatis 的开发有两种方式:
使用
MyBatis注解的方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL,建议使用 XML 来配置映射语句,也就是将SQL语句写在XML配置文件中
MyBatis XML 的方式需要以下两步:
MyBatis此步骤需要进行两项测试,数据库连接字符串设置和 MyBatis 的 XML 配置
application.yml 文件,配置内容如下mybatis:
mapper-locations: classpath:mybatis/**Mapper.xml
configuration: # 配置打印 MyBatis⽇志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# map-underscore-to-camel-case: true # 开启驼峰自动转换配置好之后,这个这个 static 目录下的这个文件名,要和 xml 里面的对应上

持久层代码分两部分:
InterfaceXXX.xml
数据持久层的接口定义
package com.glg.mybatis.mapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserInfoXmlMapper {
}在 static 里面的 mybatis 文件中,创建一个 UserInfoXmlMapper.xml,然后粘贴:
<?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.glg.mybatis.mapper.UserInfoXmlMapper">
<insert id="select">
select * from userinfo;
</insert>
</mapper><mapper> 标签:需要指定 namespace 属性,表示命名空间,值为 mapper 接口的全限定名,包括全包名、类名
<select> 查询标签:是用来执行数据库的查询操作的: id:是和 Interface (接口) 中定义的方法名称一样的,表示对接口的具体实现方法resultType:是返回的数据类型,也就是开头我们定义的实体类
UserInfoMapper 接口:
Integer insert(UserInfo userInfo);UserInfoMapper.xml 实现
<insert id="insert">
insert into userinfo (username, password, age, gender)
values (#{username}, #{password}, #{age}, #{gender});
</insert>如果使用 @Param 设置参数名称的话,使用方法和注解类似
UserInfoMapper 接口:
Integer insert(@Param("userinfo") UserInfo userInfo);UserInfoMapper.xml 实现:
<insert id="insert">
insert into userinfo (username, password, age, gender)
values (#{userinfo.username}, #{userinfo.password}, #{userinfo.age}, #{userinfo.gender});
</insert>接口定义不变,Mapper.xml 实现设置 useGeneratedKeys 和 keyProperty 属性
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into userinfo (username, password, age, gender)
values (#{userinfo.username}, #{userinfo.password}, #{userinfo.age}, #{userinfo.gender});
</insert>UserInfoMapper 接口
Integer delete(Integer id);UserInfoMapper.xml 实现:
<delete id="delete">
delete from userinfo where id = #{id};
</delete>UserInfoMapper 接口:
Integer update(UserInfo userInfo);UserInfoMapper.xml 实现:
<update id="update">
update userinfo set password = #{password} where id = #{id};
</update>同样的,使用 XML 的方式来进行查询,也存在数据封装的问题
SQL 语句进行简单修改,查询更多的字段内容UserInfoMapper 接口:
List<UserInfo> selectAllUser();UserInfoMapper,xml 实现:
<select id="selectAllUser" resultType="com.glg.mybatis.module.UserInfo">
select * from userinfo
</select>resultType:查询需要加上这个运行结果:

结果显示:deleteFlag 、createTime、updateTime 也没有进行赋值
解决方法和注解类似: