关于jdbc和代码分离自己的小方法

今天突然要写一个小的系统,因为什么都是新的,说要框架也要重新搭(bs下公司没有基础框架),ibatis自己没有怎么搭过,所以这次直接选择spring jdbc,但是要是喜欢ibatis的代码sql分离,所以自己百度了下发现spring 的jdbc代码分离有人写了,但是需要配置各个xml
,相信spring都是配置加自动的,所以自己,写了一部分,自动扫描map.xml然后加载,现在都是约定大于配置,这样我们约定放置sql的文件名和方式就可以了
下面是代码:
这个是主要的类,单例的
  1. package com.jueyue.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.concurrent.ConcurrentHashMap;
  10. import org.dom4j.Document;
  11. import org.dom4j.DocumentException;
  12. import org.dom4j.Element;
  13. import org.dom4j.io.SAXReader;
  14. import com.opensymphony.xwork2.util.logging.Logger;
  15. import com.opensymphony.xwork2.util.logging.LoggerFactory;
  16. /**
  17. * sql map的基础类
  18. * @author jueyue
  19. *
  20. */
  21. public class SQLMap {
  22.         
  23.         private static Logger logger = LoggerFactory.getLogger(SQLMap.class);
  24.         private Map<String, String> sqlContainer = null;
  25.         private String sqlFilePath = "/com/jueyue/service/impl";
  26.         
  27.         private static SQLMap instance;
  28.         
  29.         public static SQLMap getInstance(){
  30.                 if(instance == null){
  31.                         instance = new SQLMap();
  32.                 }
  33.                 return instance;
  34.         }
  35.         public SQLMap() {
  36.                 
  37.                 initSqlContainer();
  38.         }
  39.         public SQLMap(String sqlFilePath) {
  40.                 this.sqlFilePath = sqlFilePath;
  41.                 initSqlContainer();
  42.         }
  43.         public String getSql(String key) {
  44.                 String sql = sqlContainer.get(key);
  45.                 if (sql == null || "".equals(sql))
  46.                         logger.warn("不存在该SQL语句");
  47.                 if (logger.isDebugEnabled()) {
  48.                         logger.debug("SQL:" + sql);
  49.                 }
  50.                 return sql;
  51.         }
  52.         private void initSqlContainer() {
  53.                 sqlContainer = new ConcurrentHashMap<String, String>();
  54.                 if (sqlFilePath == null || "".equals(sqlFilePath)) {
  55.             throw new NullPointerException("sql语句文件不能为空!");
  56.                 }
  57.                 List<String> files = new ScanMapFile().getsqlMaps(sqlFilePath);
  58.                 for (String file : files) {
  59.                         readSQLFromFile(file);
  60.                 }
  61.         }
  62.         private void readSQLFromFile(String fileName) {
  63.                 InputStream ips = null;
  64.                 try {
  65.                         ips = new FileInputStream(new File(fileName));
  66.                 } catch (FileNotFoundException e) {
  67.                         e.printStackTrace();
  68.                 }
  69.                 Document document = null;
  70.                 SAXReader saxReader = new SAXReader();
  71.                 try {
  72.                         document = saxReader.read(ips);
  73.                 } catch (DocumentException e) {
  74.                         logger.error("读取系统中用到的SQL 语句XML出错");
  75.                         throw new RuntimeException("读取sql语句XML文件出错:" + e.getMessage());
  76.                 }
  77.                 Element root = document.getRootElement();
  78.                 @SuppressWarnings("unchecked")
  79.                 List<Element> sqlElements = (List<Element>)root.selectNodes("//sqlElement");
  80.                 String key;
  81.                 for (Element sql : sqlElements) {
  82.                         key=sql.attribute("key").getValue();
  83.                         if(sqlContainer.containsKey(key)){
  84.                                 logger.warn("key值:"+key+"重复");
  85.                         }
  86.                         sqlContainer.put(key, getSqlText(sql.getText()));
  87.                 }
  88.                 if (ips != null) {
  89.                         try {
  90.                                 ips.close();
  91.                         } catch (IOException e) {
  92.                                 logger.error("关闭输入流出错:" + e.getMessage());
  93.                         }
  94.                 }
  95.         }
  96.         /**
  97.          * 出去无效字段
  98.          */
  99.         private String getSqlText(String text) {
  100.                 return text.replaceAll("\\n", " ").replaceAll("\\t", " ");
  101.         }
  102.         public void setSqlFilePath(String sqlFilePath) {
  103.                 this.sqlFilePath = sqlFilePath;
  104.         }
  105.         @Override
  106.         protected void finalize() throws Throwable {
  107.                 super.finalize();
  108.                 if (sqlContainer != null) {
  109.                         sqlContainer.clear();
  110.                         sqlContainer = null;
  111.                 }
  112.         }
  113. }
复制代码
下面这个是扫描类
  1. package com.copote.util;
  2. import java.io.File;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. /**
  6. * 扫描service下面的所有map.xml
  7. * @author jueyue 2013年8月5日
  8. */
  9. public class ScanMapFile {
  10.         
  11.         private List<String> sqls;
  12.         
  13.         public ScanMapFile(){
  14.                 sqls =  new ArrayList<String>();
  15.         }
  16.         
  17.         public  List<String> getsqlMaps(String path){
  18.                 GetSql(ScanMapFile.class.getResource(path).getPath());
  19.                 return sqls;
  20.         }
  21.         /*
  22.          * 递归调用查找指定文件加下所有文件
  23.          */
  24.         private void GetSql(String path) {
  25.                 File rootDir = new File(path);
  26.                 if (!rootDir.isDirectory()) {
  27.                         if(rootDir.getName().equalsIgnoreCase("map.xml")){
  28.                                 sqls.add(rootDir.getAbsolutePath());
  29.                         }
  30.                 } else {
  31.                         String[] fileList = rootDir.list();
  32.                         for (int i = 0; i < fileList.length; i++) {
  33.                                 path = rootDir.getAbsolutePath() + "\\" + fileList[i];
  34.                                 GetSql(path);
  35.                         }
  36.                 }
  37.         }
  38. }
复制代码
我们扫描的是所有的map.xml这样就加载了所有的sql
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <sqls>
  3.         <sqlElement key="account.login">
  4.                 <![CDATA[
  5.                         select *  from user
  6.         </sqlElement>
  7. </sqls>
复制代码
然后在我们的dao里面这样写
  1. @Override
  2.         public AccountEntity login(AccountEntity account) {
  3.                 String sql = SQLMap.getInstance().getSql("account.login");//加载sql
  4.                 List<AccountEntity> temp = jdbcTemplate.query(sql,
  5.                                 new Object[] { account.getVAcctCode(), account.getVAcctPwd(),
  6.                                 account.getCorgId() }, new AccountRowMapper());
  7.                 return temp.size() == 1?temp.get(0):null;
  8.         }
复制代码
这样我们就获取了对于的sql,就分离了,而且自动扫描
最后记得在web.xml添加启动监听,进行初始化


jeecg 首发
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值