在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语句。