HibernateStatementSessionFactoryBean.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package com.primeton.dgs.kernel.core.dao.hibernate;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.Serializable;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.Iterator;
  9. import java.util.List;
  10. import java.util.Map;
  11. import java.util.Optional;
  12. import java.util.concurrent.atomic.AtomicInteger;
  13. import org.jdom.Document;
  14. import org.jdom.Element;
  15. import org.jdom.JDOMException;
  16. import org.jdom.Text;
  17. import org.jdom.input.SAXBuilder;
  18. import org.slf4j.Logger;
  19. import org.slf4j.LoggerFactory;
  20. import org.springframework.core.io.Resource;
  21. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  22. import org.springframework.core.io.support.ResourcePatternResolver;
  23. import com.primeton.dgs.kernel.core.ex.HibernateStatementException;
  24. import com.primeton.dgs.kernel.core.util.MetadataWebContext;
  25. public class HibernateStatementSessionFactoryBean implements Serializable {
  26. private static final long serialVersionUID = 1L;
  27. private static final String PREFIX = "META-INF/sqlxml/"; // 加载模块的SQL文件的路径前缀
  28. private static final String ENDFIX = "*Sql.xml"; // 文件名的扩展后缀名
  29. final DatabaseRecognizer databaseRecognizer;
  30. private HibernateStatementSessionFactoryBean parent;
  31. private static HibernateStatementSessionFactoryBean instance;
  32. private Map<String, List<HibernateStatementField>> statements;
  33. private boolean ready = false;
  34. private Resource[] statementLocations;
  35. private boolean merge = false;
  36. public HibernateStatementSessionFactoryBean(DatabaseRecognizer databaseRecognizer) {
  37. instance = this;
  38. this.databaseRecognizer = databaseRecognizer;
  39. this.statements = new HashMap();
  40. }
  41. public void setStatementResources(String[] statementResources) {
  42. setStatementResources();
  43. }
  44. public void setStatementLocations(File[] statementLocations) {
  45. setStatementResources();
  46. }
  47. public void setStatementLocations(Resource[] statementLocations) {
  48. this.statementLocations = statementLocations;
  49. }
  50. public void setStatementResources(String statementResources) {
  51. setStatementResources();
  52. }
  53. private void setStatementResources() {
  54. try {
  55. //TODO 不同数据库,要区别加载数据文件
  56. ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
  57. statementLocations = resolver.getResources("classpath*:"
  58. .concat(PREFIX)
  59. .concat(databaseRecognizer.getDbType()).concat("/").concat(ENDFIX));
  60. } catch (IOException e) {
  61. log.error("加载 Native QuerySQL 异常。", e);
  62. }
  63. }
  64. public Resource[] getStatementLocations() {
  65. return this.statementLocations;
  66. }
  67. public boolean isReady() {
  68. return this.ready;
  69. }
  70. public HibernateStatementSessionFactoryBean getParent() {
  71. return this.parent;
  72. }
  73. public void setParent(HibernateStatementSessionFactoryBean parent) {
  74. this.parent = parent;
  75. }
  76. public boolean isMerge() {
  77. return this.merge;
  78. }
  79. public void setMerge(boolean merge) {
  80. this.merge = merge;
  81. }
  82. public void init() throws IOException {
  83. this.ready = false;
  84. this.statements.clear();
  85. for (int i = 0; i < this.statementLocations.length; i++) {
  86. try(final InputStream inputStream = this.statementLocations[i].getInputStream();) {
  87. config(inputStream);
  88. log.info("read xml sql template file: {}", statementLocations[i].getURI());
  89. } catch (Exception e) {
  90. log.error("parse sql xml error.", e);
  91. }
  92. }
  93. if ((isMerge()) && (this.parent != null)) {
  94. doMerge();
  95. }
  96. this.ready = true;
  97. }
  98. private void doMerge() {
  99. if (this.parent != null)
  100. for (Iterator it = this.statements.keySet().iterator(); it
  101. .hasNext();) {
  102. String key = (String) it.next();
  103. if (this.parent.statements.containsKey(key)) {
  104. throw new HibernateStatementException("statement of id=\""
  105. + key + "\" has bean defined!");
  106. }
  107. this.parent.statements.put(key, (List) this.statements.get(key));
  108. }
  109. }
  110. public void config(InputStream in) throws IOException {
  111. SAXBuilder sb = new SAXBuilder();
  112. try {
  113. Document doc = sb.build(in);
  114. Element root = doc.getRootElement();
  115. List statements = root.getChildren("statement");
  116. for (int i = 0; i < statements.size(); i++) {
  117. Element stmt = (Element) statements.get(i);
  118. String id = stmt.getAttributeValue("id");
  119. if ((id == null) || ("".equals(id.trim()))) {
  120. throw new HibernateStatementException(
  121. "statement''s \"id\" should not be empty!");
  122. }
  123. if (this.statements.containsKey(id)) {
  124. throw new HibernateStatementException("statement of id=\""
  125. + id + "\" has bean defined!");
  126. }
  127. List fields = stmt.getContent();
  128. this.statements.put(id, readFields(fields));
  129. }
  130. } catch (JDOMException e) {
  131. throw new HibernateStatementException("statement file is error!", e);
  132. } catch (IOException e) {
  133. throw new HibernateStatementException("statement file not exist!",
  134. e);
  135. } finally {
  136. if (in != null)
  137. in.close();
  138. }
  139. }
  140. private List<HibernateStatementField> readFields(List<?> fields) {
  141. List result = new ArrayList();
  142. for (int j = 0; j < fields.size(); j++) {
  143. if ((fields.get(j) instanceof Text)) {
  144. String text = ((Text) fields.get(j)).getTextTrim();
  145. if (!"".equals(text)) {
  146. result.add(new HibernateStatementTextField(text));
  147. }
  148. } else if ((fields.get(j) instanceof Element)) {
  149. Element field = (Element) fields.get(j);
  150. if ("dynamic-field".equals(field.getName())) {
  151. result.add(readDynamicField(field));
  152. } else if ("compare-field".equals(field.getName())) {
  153. result.add(readCompareField(field));
  154. } else {
  155. throw new HibernateStatementException("\""
  156. + field.getName() + "\" is not supportable!");
  157. }
  158. }
  159. }
  160. return result;
  161. }
  162. private HibernateStatementDynamicField readDynamicField(Element field) {
  163. String property = field.getAttributeValue("property");
  164. String onEmpty = field.getAttributeValue("onEmpty");
  165. if ((property == null) || ("".equals(property))) {
  166. throw new HibernateStatementException(
  167. "\"property\" of dynamic-field is required!");
  168. }
  169. HibernateStatementDynamicField f = new HibernateStatementDynamicField(
  170. property, onEmpty);
  171. List children = readFields(field.getContent());
  172. f.getChildren().addAll(children);
  173. return f;
  174. }
  175. private HibernateStatementCompareField readCompareField(Element field) {
  176. String compare = field.getAttributeValue("compare");
  177. String compareProperty = field.getAttributeValue("compareProperty");
  178. String compareValue = field.getAttributeValue("compareValue");
  179. if ((compare == null) || ("".equals(compare))) {
  180. throw new HibernateStatementException(
  181. "Attribute \"compare\" of compare-field is required!");
  182. }
  183. if ((compareProperty == null) || ("".equals(compareProperty))) {
  184. throw new HibernateStatementException(
  185. "Attribute \"compareProperty\" of compare-field is required!");
  186. }
  187. if ((compareValue == null)) {
  188. throw new HibernateStatementException(
  189. "Attribute \"compareValue\" of compare-field is required!");
  190. }
  191. if (!HibernateStatementCompareField.isAvailableCompare(compare)) {
  192. throw new HibernateStatementException(
  193. "Attribute \"compare\" of compare-field is unavailable, the available value is (" + HibernateStatementCompareField.AVAILABLE_COMPARE + ")!");
  194. }
  195. HibernateStatementCompareField f = new HibernateStatementCompareField(
  196. compare, compareProperty, compareValue);
  197. List children = readFields(field.getContent());
  198. f.getChildren().addAll(children);
  199. return f;
  200. }
  201. public void destroy() {
  202. this.statements.clear();
  203. this.ready = false;
  204. }
  205. public void refresh() throws IOException {
  206. destroy();
  207. init();
  208. }
  209. public List<HibernateStatementField> getStatement(String id) {
  210. List<HibernateStatementField> statementFields = this.statements.get(id);
  211. if (statementFields == null) {
  212. if (this.parent == null) {
  213. log.error("statement [id=\"" + id+ "\"]: not existed");
  214. /*throw new HibernateStatementException("statement [id=\"" + id
  215. + "\"]: not existed");*/
  216. return null;
  217. }
  218. return this.parent.getStatement(id);
  219. }
  220. return (List) statementFields;
  221. }
  222. public String getText(String id) {
  223. return getText(id, null);
  224. }
  225. public String getText(String id, Object vo) {
  226. List<?> fileds = getStatement(id);
  227. if(null == fileds){
  228. return null;
  229. }
  230. StringBuffer sb = new StringBuffer();
  231. AtomicInteger index = new AtomicInteger(1);
  232. try {
  233. for (int i = 0; i < fileds.size(); i++) {
  234. StringBuffer s = ((HibernateStatementField) fileds.get(i)).getText(vo, index);
  235. if ((s != null) && (s.length() > 0))
  236. sb.append(s).append(" ");
  237. }
  238. } catch (NumberFormatException e) {
  239. throw new HibernateStatementException("statement [id=\"" + id
  240. + "\"]: cannot format number " + e.getMessage());
  241. } catch (Exception e) {
  242. throw new HibernateStatementException("statement [id=\"" + id
  243. + "\"]: " + e.getMessage(), e);
  244. }
  245. return sb.toString();
  246. }
  247. public static String getStatementText(String id) {
  248. return getStatementText(id, null);
  249. }
  250. public static String getStatementText(String id, Object vo) {
  251. return instance.getText(id, vo);
  252. }
  253. public Object[] getParam(String id, Object vo) {
  254. List fileds = Optional.ofNullable(getStatement(id)).orElse(new ArrayList<>(0));
  255. List result = new ArrayList();
  256. for (int i = 0; i < fileds.size(); i++) {
  257. List list = ((HibernateStatementField) fileds.get(i)).getParam(vo);
  258. if ((list != null) && (!list.isEmpty())) {
  259. result.addAll(list);
  260. }
  261. }
  262. return result.toArray();
  263. }
  264. public Map<String, Object> getParamMap(String id, Object vo) {
  265. if (!this.statements.containsKey(id)) {
  266. throw new HibernateStatementException("statement [id=\"" + id
  267. + "\"]: not existed");
  268. }
  269. Map result = new HashMap();
  270. List fileds = getStatement(id);
  271. for (int i = 0; i < fileds.size(); i++) {
  272. Map map = ((HibernateStatementField) fileds.get(i)).getParamMap(vo);
  273. if ((map != null) && (!map.isEmpty())) {
  274. result.putAll(map);
  275. }
  276. }
  277. return result;
  278. }
  279. public static Object[] getStatementParam(String id, Object vo) {
  280. return instance.getParam(id, vo);
  281. }
  282. public static Map<String, Object> getStatementParamMap(String id, Object vo) {
  283. return instance.getParamMap(id, vo);
  284. }
  285. public static boolean isStateReady() {
  286. return instance.isReady();
  287. }
  288. public static void main(String[] args) throws Exception {
  289. final DatabaseRecognizer databaseRecognizer = new DatabaseRecognizer();
  290. databaseRecognizer.setDbType("mysql");
  291. HibernateStatementSessionFactoryBean factoryBean = new HibernateStatementSessionFactoryBean(databaseRecognizer);
  292. factoryBean.setStatementResources("");
  293. factoryBean.init();
  294. final HashMap<Object, Object> vo = new HashMap<>();
  295. vo.put("code", "abc");
  296. vo.put("parentId", "ttttt");
  297. vo.put("num", "ss");
  298. vo.put("num2", null);
  299. System.out.println(factoryBean.getText("onlyOneEndByCode", vo));
  300. System.out.println(Arrays.asList(factoryBean.getParam("onlyOneEndByCode", vo)));
  301. }
  302. }