10.3 MyBatis调用存储过程 10.3.3根据id查询数据返回对象 创建存储过程 在之前创建的mybatis
数据库中创建一个根据id
查询tb_user
表对应数据的存储过程,SQL
脚本如下:
1 2 3 4 5 6 7 8 drop procedure if exists select_user_by_id;delimiter $$ create procedure select_user_by_id(IN in_id INTEGER )begin select id,name,sex,age from tb_user where id= in_id; end $$ delimiter ;
创建映射标签 在UserMapper.xml
中加入调用名为”select_user_by_id
“的存储过程的select
元素,如下代码所示:
1 2 3 4 5 6 7 8 <select id ="selectUserById" parameterType ="int" resultType ="domain.User" statementType ="CALLABLE" > { call select_user_by_id(#{id,mode=IN}) } </select >
mapper接口方法 1 User selectUserById (Integer id) ;
测试类 /MyProcedureTest/src/test/SelectByIdTest.java 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package test;import org.apache.ibatis.session.SqlSession;import domain.User;import fractory.SqlSessionFactoryTools;import mapper.UserMapper;public class SelectByIdTest { public static void main (String[] args) { SqlSession sqlSession = null ; sqlSession = SqlSessionFactoryTools.getSqlSession(); try { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.selectUserById(1 ); System.out.println(" " + user); sqlSession.commit(); } catch (Exception e) { sqlSession.rollback(); e.printStackTrace(); } finally { if (sqlSession != null ) { sqlSession.close(); } } } }
运行效果 1 2 3 4 5 DEBUG [main] ==> Preparing: {call select_user_by_id(?)} DEBUG [main] ==> Parameters: 1 (Integer) DEBUG [main] <== Total: 1 DEBUG [main] <== Updates: 0 User [id=1 , name=小明, sex=男, age=21 ]