在MyBatis中,Mapper接口可以通過以下步驟來實現:
public interface UserMapper {
User getUserById(int id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
<?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.UserMapper">
<select id="getUserById" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="User">
INSERT INTO users (id, name, age) VALUES (#{id}, #{name}, #{age})
</insert>
<update id="updateUser" parameterType="User">
UPDATE users SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="deleteUser">
DELETE FROM users WHERE id = #{id}
</delete>
</mapper>
<configuration>
<mappers>
<mapper resource="com/example/UserMapper.xml" />
</mappers>
</configuration>
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 查詢用戶信息
User user = userMapper.getUserById(1);
System.out.println(user);
// 插入用戶信息
User newUser = new User(2, "Alice", 25);
userMapper.insertUser(newUser);
// 更新用戶信息
newUser.setAge(30);
userMapper.updateUser(newUser);
// 刪除用戶信息
userMapper.deleteUser(2);
sqlSession.commit();
sqlSession.close();
通過以上步驟,就可以實現MyBatis中的Mapper接口。在實際應用中,可以根據具體的需求和業務邏輯來編寫Mapper接口和對應的SQL語句。