Mybatis中執行String類型的自己拚寫的sql,不執行配置文件中的sql
Mybatis中執行String類型的自己拚寫的sql,不執行配置文件中的sql在自己的dao類中繼承SqlSessionDaoSupport類
/** * @author herman.xiong * @since 0.1 * @param <T>實體類 * @param <PK>主鍵類,必須實現Serializable接口 */ package com.dao; import java.io.Serializable; import org.apache.log4j.Logger; import org.mybatis.spring.support.SqlSessionDaoSupport; import java.util.ArrayList; import java.util.List; public class TestSqlDao extends SqlSessionDaoSupport{ //日誌管理器 private static final Logger log=Logger.getLogger(TestSqlDao.class); //測試自己拚寫的sql public List<Integer> testStringSql(String sql){ List<Integer> list=new ArrayList<Integer>(); Connection con=this.getSqlSession().getConnection(); PreparedStatement ps=null; ResultSet rs=null; try { ps = con.prepareStatement(sql); rs=ps.executeQuery(); while (rs.next()) { list.add(rs.getInt("id")); } } catch (Exception e) { e.printStackTrace(); } finally { if(rs!=null){ try { rs.close(); } catch (Exception e) { log.error("關閉結果集ResultSet異常!"+e.getMessage(), e); } } if(ps!=null){ try { ps.close(); } catch (Exception e) { log.error("預編譯SQL語句對象PreparedStatement關閉異常!"+e.getMessage(), e); } } if(con!=null){ try { con.close(); } catch (Exception e) { log.error("關閉連接對象Connection異常!"+e.getMessage(), e); } } } return list; } public static void main(String[] args) { TestSqlDao tsd=new TestSqlDao(); List<Integer> list=tsd.testStringSql("select id from table"); for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); } } }
一下是本人自己測試的輸出結果截圖:
最後更新:2017-04-03 12:55:25