Create MyBatis Mappers: Complete Guide
Creating a mapper in MyBatis usually involves the following steps:
- Create a mapper interface: Start by creating an interface with the typical naming convention of xxxMapper, where xxx represents the name of the corresponding data table or entity class.
public interface UserMapper {
User selectUserById(int userId);
void insertUser(User user);
void updateUser(User user);
void deleteUser(int userId);
}
- Create a mapper XML file: Create a XML file with the same name as the mapper interface in the resources directory, to write SQL statements and mapping relationships.
<?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.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="com.example.model.User">
SELECT * FROM user WHERE id = #{userId}
</select>
<insert id="insertUser" parameterType="com.example.model.User">
INSERT INTO user (id, name, age) VALUES (#{id}, #{name}, #{age})
</insert>
<update id="updateUser" parameterType="com.example.model.User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM user WHERE id = #{userId}
</delete>
</mapper>
- Configure Mapper interface and XML file: Add the scanning and configuration of mapper in MyBatis configuration file (usually mybatis-config.xml).
<configuration>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
- Use mapper: In the code, retrieve the implementation of the mapper interface through MyBatis’s SqlSession object, and then invoke the methods in the interface to execute database operations.
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectUserById(1);
user.setAge(30);
userMapper.updateUser(user);
sqlSession.commit();
sqlSession.close();
By following the above steps, you can create a mapper in MyBatis and start using it.