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));
		}
	}
}

猜你喜欢

转载自blog.csdn.net/guoruijun_2012_4/article/details/83014976