在MyBatis中使用存儲過程可以通過Mapper接口的方式來實現。下面是一個使用存儲過程的示例:
CREATE PROCEDURE GetUserInfo(IN userId INT, OUT userName VARCHAR(255))
BEGIN
SELECT user_name INTO userName
FROM user
WHERE user_id = userId;
END
public interface UserMapper {
@Select("{call GetUserInfo(#{userId, jdbcType=INTEGER, mode=IN}, #{userName, jdbcType=VARCHAR, mode=OUT})}")
void getUserInfo(@Param("userId") int userId, @Param("userName") String userName);
}
<mapper namespace="com.example.UserMapper">
<select id="getUserInfo" statementType="CALLABLE">
{call GetUserInfo(#{userId, mode=IN, jdbcType=INTEGER}, #{userName, mode=OUT, jdbcType=VARCHAR})}
</select>
</mapper>
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
String userName = null;
userMapper.getUserInfo(1, userName);
System.out.println("User name: " + userName);
通過以上步驟,就可以在MyBatis中使用存儲過程來獲取數據。