之前在调用postgresql的存储过程时,还是使用传统的方法,没有充分利用mybatis框架,代码如下所示:
@Override
public String getBinById(String id) {
String name = null;
Connection conn = null;
try {
conn = dataSource.getConnection();
CallableStatement properCase = conn.prepareCall("{ ? = call bin_info.getbname( ? ) }");
properCase.setString(2,id);
properCase.registerOutParameter(1, Types.VARCHAR);
properCase.execute();
name = properCase.getString(1);
log.info("the name of {} is {} ",id,name);
} catch (SQLException e) {
e.printStackTrace();
}
return name;
}
虽然可以成功调用,但是大部分内容框架都帮我们做了,何必再要自己写一遍,从而增加出错的概率。使用框架后的结果如下:
Mapper 层
@Select("SELECT bin_info.getbname(#{gId})")
String getBinNameByGId(@Param("gId")String gId);
注:mybatis 调用postgresql的存储过程使用的是select,区别于mysql中的call
Service 层
@Override
public String getBinById(String id) {
String name = null;
try {
name = binMapper.getBinNameByGId(id);
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
非常简单,除去捕获异常的代码,一行代码就能搞定