package com.whyc.service;
|
|
import com.whyc.mapper.CallBack;
|
import org.apache.ibatis.session.SqlSession;
|
import org.apache.ibatis.session.SqlSessionFactory;
|
import org.mybatis.spring.SqlSessionTemplate;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.stereotype.Service;
|
|
import java.sql.PreparedStatement;
|
import java.sql.ResultSet;
|
import java.sql.SQLException;
|
import java.util.List;
|
|
@Service
|
public class MybatisSqlExecuteService {
|
@Autowired
|
private SqlSessionTemplate sqlSessionTemplate;
|
|
// 自定义执行SQL
|
public List executeQuery(String sql, CallBack call){
|
PreparedStatement ps = null;
|
ResultSet rs = null;
|
SqlSession sqlSession = openSession();
|
try {
|
ps=sqlSession.getConnection().prepareStatement(sql);
|
rs=ps.executeQuery();
|
return call.getResults(rs);
|
} catch (SQLException throwables) {
|
throwables.printStackTrace();
|
}finally {
|
closeSession(rs,ps,sqlSession);
|
}
|
return null;
|
}
|
|
// 开启链接
|
private SqlSession openSession() {
|
SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
|
return sqlSessionFactory.openSession();
|
}
|
|
// 关闭链接
|
private void closeSession(ResultSet rs,PreparedStatement ps,SqlSession sqlSession) {
|
try {
|
rs.close();
|
ps.close();
|
sqlSession.close();
|
} catch (SQLException throwables) {
|
throwables.printStackTrace();
|
}
|
}
|
}
|