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语句。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: 在MyBatis项目中如何优化事务管理