在MyBatis中創(chuàng)建一個mapper通常分為以下幾個步驟:
public interface UserMapper {
User selectUserById(int userId);
void insertUser(User user);
void updateUser(User user);
void deleteUser(int userId);
}
<?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>
<configuration>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
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();
通過以上步驟,就可以在MyBatis中創(chuàng)建一個mapper并使用。