目录
配置xml文件
一,查询 - Select
1.1 全列查询
1.2 赋值问题
二,新增 - insert
2.1 使用对象插入
2.2 获取主键
三,删除 - delete
四,修改 - update
配置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.example.javaeespringioc.mapper.UserInfoXmlMapper">
#增删查改都在这里实现
</mapper>
一,查询 - Select
1.1 全列查询
@Mapper
public interface UserInfoXmlMapper {
List<UserInfo> queryUserList();
}
<select id="queryUserList" resultType="com.example.javaeespringioc.controller.UserInfo">
select * from userInfo;
</select>
1.2 赋值问题
可以发现,在赋值时,xml 也出现了 deleteFlag,createTime,updateTime 并没有被赋值的问题,出现的原因还是MySQL中的字段名与Java对象中的属性名不相同。
有三种解决方法:1.起别名;2.结果映射;3.添加配置。其中1,3方法与注解版相同就不过多赘述,这里只演示方法二。
<resultMap id="BaseMap" type="com.example.javaeespringioc.controller.UserInfo"> <id column="id" property="id"></id> <result column="delete_flag" property="deleteFlag"></result> <result column="create_time" property="createTime"></result> <result column="update_time" property="updateTime"></result> </resultMap> <select id="queryUserList" resultMap="BaseMap"> select * from userInfo; </select>
二,新增 - insert
2.1 使用对象插入
@Mapper
public interface UserInfoXmlMapper {
Integer insertUserInfo(UserInfo userInfo);
}
<insert id="insertUserInfo">
insert into userInfo (username, password, age, gender, phone) values (#{username}, #{password}, #{age}, #{gender}, #{phone})
</insert>
2.2 获取主键
<insert id="insertUserInfo" useGeneratedKeys="true" keyProperty="id">
insert into userInfo (username, password, age, gender, phone) values (#{username}, #{password}, #{age}, #{gender}, #{phone})
</insert>
三,删除 - delete
@Mapper
public interface UserInfoXmlMapper {
Integer deleteUserInfo(Integer id);
}
<delete id="deleteUserInfo">
delete from userInfo where id = #{id}
</delete>
四,修改 - update
@Mapper
public interface UserInfoXmlMapper {
Integer updateUserInfo(UserInfo userInfo);
}
<update id="updateUserInfo">
update userInfo set username = #{username} where id = #{id}
</update>