ITeye博客

有关读数据库的无刷新的三级联动以及层次数据(树形结构)在关系数据库的存储

syhan · 2007-04-11 11:26 · java · Markdown

我的标题真冗长:P

最近一直在考虑这个问题,如何在现在常用的关系型数据库(如mysql,mssql)中存储含有层次结构(例如xml或者树型结构)的数据,我最终要实现的结果是一个比较好的页面三级联动菜单。比较了一下现有的三级联动,无非有两种解决方案,1、将所有数据写成静态的,这样的缺点在于对更新封闭;2、每改变一次去数据库中获取数据,填充到下一级菜单,这个缺点是对数据库的开销比较大,查询一次数据要对数据库做三次操作,而且数据库设计的比较丑陋。上述两种方法都让我比较不能接受。

我想的是一种比较优雅的解决方案:在数据库中存储的数据不要冗余,便于查询,不要产生递归,对数据库的开销要尽可能的小,尽量做到一次将所有数据都读出来,用户也要有比较好的体验。我最初的解决方案就是用xml来存储联动的数据,但是对于数据库操作来说,最后还是要落实到对文件的I/O操作,从这方面来讲,使用xml和数据库并没有什么本质的不同。另外一种解决方案就是在关系数据库中存类xml的数据了。google了半天,最后发现了一片自己学院一位学长翻译的文章www.nirvanastudio.org/category/database,讲得就是如何在关系型数据库存储这种层次数据的。文中提出了两种解决方案,一是“邻接列表模型”或称为“递归方法”,这种存在着数据冗余,而且递归出于众所周知的原因,效率不高。第二种方法,也就是我现在采用的方法是"前序优先遍历",表结构也很简单,没有冗余

id name left right

我觉得应该属于一种深度优先。通过每个节点的左右两个属性获得其子女的属性,好处就在于获得一个或几个节点只需要一次查询,而在更新的时候速度会比较慢,因为要更新多个后继节点,不过话说回来,更新相对于获取来说次数要少的多,可以忽略。

下面是我的解决方案:

java 代码

 

  1. import java.io.IOException;
  2. import java.sql.Connection;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.ArrayList;
  7. import com.netkc.struts.datasource.DataSource;
  8. import com.netkc.struts.mapping.District;
  9. /**
  10. * @author SONG Yihan
  11. * @version 1.0
  12. * @date: Monday, April 09 2007
  13. */
  14. public class DistrictTree {
  15. private ArrayList<district> tree;  </district>
  16. private Statement stmt1 = null;
  17. private Statement stmt2 = null;
  18. private Connection conn = null;
  19. private ResultSet rs = null;
  20. public DistrictTree() {
  21. try {
  22. conn = DataSource.getConnection();
  23. } catch (IOException e) {
  24. // TODO Auto-generated catch block
  25. e.printStackTrace();
  26. } catch (SQLException e) {
  27. // TODO Auto-generated catch block
  28. e.printStackTrace();
  29. } catch (ClassNotFoundException e) {
  30. // TODO Auto-generated catch block
  31. e.printStackTrace();
  32. } catch (InstantiationException e) {
  33. // TODO Auto-generated catch block
  34. e.printStackTrace();
  35. } catch (IllegalAccessException e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. }
  39. }
  40. public DistrictTree(Connection conn) {
  41. this.conn = conn;
  42. }
  43. public boolean addNode(String parentId, String districtId, String districtName) {
  44. try {
  45. String sql = "SELECT * FROM district WHERE districtId='" + parentId + "';";
  46. conn.setAutoCommit(false);
  47. stmt1 = conn.createStatement();
  48. rs = stmt1.executeQuery(sql);
  49. if(rs.next()) {
  50. int right = rs.getInt("rgt");
  51. sql = "UPDATE district SET lft=lft+2 WHERE lft>=" + right;
  52. stmt2.addBatch(sql);
  53. sql = "UPDATE district SET rgt=rgt+2 WHERE rgt>=" + right;
  54. stmt2.addBatch(sql);
  55. sql = "INSERT INTO district (districtId, districtName, lft, rgt) VALUES ('"+districtId + "', '" + districtName + "', " +
  56. (right) + ", " + (right+1) +");";
  57. stmt2.addBatch(sql);
  58. int[] flag = stmt2.executeBatch();
  59. if(flag[flag.length - 1] == 1) {
  60. conn.commit();
  61. return true;
  62. } else {
  63. conn.rollback();
  64. return false;
  65. }
  66. }
  67. } catch (SQLException e) {
  68. // TODO Auto-generated catch block
  69. e.printStackTrace();
  70. } finally {
  71. }
  72. return false;
  73. }
  74. public boolean deleteNode(String districtId) {
  75. String sql = "SELECT * FROM district WHERE districtId='" + districtId + "';";
  76. try {
  77. conn.setAutoCommit(false);
  78. rs = stmt1.executeQuery(sql);
  79. if(rs.next())
  80. {
  81. int left = rs.getInt("lft");
  82. int right = rs.getInt("rgt");
  83. int count = (right - left - 1) / 2 + 1;
  84. int minus = count * 2;
  85. sql = "DELETE FROM district WHERE lft BETWEEN " + left + " AND " + right + ";";
  86. stmt2.addBatch(sql);
  87. sql = "UPDATE district SET lft=lft-" + minus + " WHERE lft>"+right;
  88. stmt2.addBatch(sql);
  89. sql = "UPDATE district SET rgt=rgt-" + minus + " WHERE rgt>"+right;
  90. stmt2.addBatch(sql);
  91. int flag = stmt2.executeBatch()[0];
  92. if(flag == 1) {
  93. conn.commit();
  94. return true;
  95. } else {
  96. conn.rollback();
  97. return false;
  98. }
  99. }
  100. } catch (SQLException e) {
  101. // TODO Auto-generated catch block
  102. e.printStackTrace();
  103. }
  104. return false;
  105. }
  106. public void displayTree(String parentId) {
  107. }
  108. public ArrayList<district> getTree(String parentId) {  </district>
  109. String sql = "SELECT * FROM district WHERE districtId='" + parentId + "';";
  110. try {
  111. stmt1 = conn.createStatement();
  112. rs = stmt1.executeQuery(sql);
  113. if(rs.next()) {
  114. int left = rs.getInt("lft");
  115. int right = rs.getInt("rgt");
  116. stmt2 = conn.createStatement();
  117. sql = "SELECT * FROM district WHERE lft BETWEEN " + left + " AND " + right + " ORDER BY lft ASC";
  118. rs = stmt2.executeQuery(sql);
  119. tree = new ArrayList<district>();  </district>
  120. District district = null;
  121. while(rs.next()) {
  122. district = new District();
  123. district.setDistrictId(rs.getString("districtId"));
  124. district.setDistrictName(rs.getString("districtName"));
  125. district.setLeft(rs.getInt("lft"));
  126. district.setRight(rs.getInt("rgt"));
  127. tree.add(district);
  128. }
  129. return tree;
  130. }
  131. } catch (SQLException e) {
  132. // TODO Auto-generated catch block
  133. e.printStackTrace();
  134. } finally {
  135. try {
  136. if (rs != null) {
  137. rs.close();
  138. }
  139. stmt1.close();
  140. stmt2.close();
  141. conn.close();
  142. } catch (SQLException e) {
  143. // TODO Auto-generated catch block
  144. e.printStackTrace();
  145. }
  146. }
  147. return null;
  148. }
  149. public ArrayList<district> getChildren(String parentId) {  </district>
  150. if(tree == null) {
  151. tree = getTree(parentId);
  152. }
  153. ArrayList<district> children = new ArrayList<district>();  </district></district>
  154. int index = this.indexof(parentId);
  155. if(index != -1) {
  156. District d = tree.get(index);
  157. final int count = (d.getRight() - d.getLeft() - 1) / 2;
  158. for(int i = index + 1; i <= index + count; i++) {
  159. d = tree.get(i);
  160. children.add(d);
  161. i += (d.getRight() - d.getLeft() - 1) / 2;
  162. }
  163. }
  164. return children;
  165. }
  166. private int indexof(String districtId) {
  167. for(int index = 0; index < tree.size(); index++) {
  168. if(districtId.equals(tree.get(index).getDistrictId())) {
  169. return index;
  170. }
  171. }
  172. return -1;
  173. }
  174. public boolean updateNode(String districtId, String districtName) {
  175. String sql = "UPDATE district SET districtName='" + districtName + "' WHERE districtId='" + districtId + "';";
  176. try {
  177. conn.setAutoCommit(false);
  178. stmt1 = conn.createStatement();
  179. int flag = stmt1.executeUpdate(sql);
  180. if(flag == 1) {
  181. conn.commit();
  182. return true;
  183. }
  184. else {
  185. conn.rollback();
  186. return false;
  187. }
  188. } catch (SQLException e) {
  189. // TODO Auto-generated catch block
  190. e.printStackTrace();
  191. } finally {
  192. }
  193. return false;
  194. }
  195. }

这个最遗憾的地方就是在其中混杂了java代码,这让我及其不爽,但是我没有找到向js传值的好办法:(

js 代码

 

  1. function District(id, name, left, right) {
  2. this.id=id;
  3. this.name=name;
  4. this.left=left;
  5. this.right=right;
  6. };
  7. var tree = new Array();
  8. <%
  9. for(District d : tree) {
  10. %>  tree.push(new District('<%=d.getDistrictId()%>', '<%=d.getDistrictName()%>', '<%=d.getLeft()%>', '<%=d.getRight()%>'));
  11. <%}%>
  12. Array.prototype.indexof = function(id) {
  13. for(var index = 0; index < tree.length; index++) {
  14. if(id == tree[index].id) {
  15. return index;
  16. }
  17. }
  18. return -1;
  19. };
  20. function citychanged(id){
  21. document.getElementById('district').length = 0;
  22. document.getElementById('area').length = 0;
  23. var districts = getChildren(id);
  24. for(var i = 0; i < districts.length; i++){
  25. document.getElementById('district').options[i] = new Option(districts[i].name, districts[i].id);
  26. }
  27. };
  28. function districtchanged(id) {
  29. document.getElementById('area').length = 0;
  30. var area = getChildren(id);
  31. for(var i = 0; i < area.length; i++){
  32. document.getElementById('area').options[i] = new Option(area[i].name, area[i].id);
  33. }
  34. };
  35. function getChildren(id) {
  36. if(tree.length == 0) {
  37. }
  38. var children = new Array();
  39. var index = tree.indexof(id);
  40. if(index != -1) {
  41. var d = tree[index];
  42. var count = (d.right - d.left - 1) / 2;
  43. for(var i = index + 1; i <= index + count; i++) {
  44. d = tree[i];
  45. children.push(d);
  46. i += (d.right - d.left - 1) / 2;
  47. }
  48. }
  49. return children;
  50. };

 

jsp 页面 代码

 

  1. "/fastfoodAct?method=query" styleId="queryFoodForm">
  2. searchType :
  3. city :
  4. district :
  5. area :
  6. restaurantName :
  7. searchType :
  8. foodName :
  9. <html:submit> <html:cancel>    </html:cancel> </html:submit>

 

以上就是我解决三级联动和层次结构的一点想法:)

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。