在介面對映中新增方法,UserMapper
public interface UserMapper {
List<User> getUserList();
User getUserById(int id);
void addUser(User user);
void delUser(int id);
}
在UserMapper.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.Dao.UserMapper">
<select id="getUserList" resultType="com.example.pojo.User">
select * from mybatis.user;
</select>
<select id="getUserById" resultType="com.example.pojo.User" parameterType="int">
select * from mybatis.user where id = #{id};
</select>
<insert id="addUser" parameterType="com.example.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<delete id="delUser" parameterType="int">
delete from mybatis.user where id=${id};
</delete>
</mapper>
標籤屬性解析
屬性 | 值的描述 |
---|---|
id | 介面的方法名 |
resultType | 返回結果物件的全類名 |
parameterType | 引數物件的全類名 |
#{XX}. | XX為SQL的欄位名 (忽略.) |
如果出現異常
Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 7; columnNumber: 9; 1 位元組的 UTF-8 序列的位元組 1 無效。
因為該XML檔案中的註釋導致亂碼了,要麼修改encoding要麼刪除中文註釋
對於上述的增刪改操作。要求手動提交事務。
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(new User(4,"老六","55555"));
sqlSession.commit();
sqlSession.close();