MyBatis的mapper是用于映射數據庫操作的接口,通過這個接口可以方便地調用SQL語句進行數據庫的增刪改查操作。
使用步驟如下:
MyMapper
(示例名稱),并在接口中定義數據庫操作的方法。public interface MyMapper {
void insert(MyObject myObject);
void update(MyObject myObject);
void delete(int id);
MyObject select(int id);
}
MyMapper.xml
,并在該文件中編寫對應的SQL語句。<?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.MyMapper">
<insert id="insert" parameterType="com.example.MyObject">
INSERT INTO my_table (id, name) VALUES (#{id}, #{name})
</insert>
<update id="update" parameterType="com.example.MyObject">
UPDATE my_table SET name = #{name} WHERE id = #{id}
</update>
<delete id="delete" parameterType="int">
DELETE FROM my_table WHERE id = #{id}
</delete>
<select id="select" parameterType="int" resultType="com.example.MyObject">
SELECT id, name FROM my_table WHERE id = #{id}
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="com/example/MyMapper.xml"/>
</mappers>
</configuration>
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
MyMapper mapper = sqlSession.getMapper(MyMapper.class);
// 插入數據
MyObject myObject = new MyObject();
myObject.setId(1);
myObject.setName("test");
mapper.insert(myObject);
// 更新數據
myObject.setName("test2");
mapper.update(myObject);
// 刪除數據
mapper.delete(1);
// 查詢數據
MyObject result = mapper.select(1);
System.out.println(result);
} finally {
sqlSession.close();
}
以上就是使用MyBatis的mapper的基本步驟,你可以根據自己的需求來定義接口和編寫SQL語句。