天天看點

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

目錄

多表查詢UI界面

添加的主要模闆

最終運作效果

距離上次代碼生成器更新已經兩周多了,最近太忙,一直沒顧上更新,這兩天難得清靜,于是在原來的基礎上增加了多表查詢的功能,修複了以前的一些bug,讓我們進入正題吧。

多表查詢UI界面

首先是多表查詢的ui界面,同樣采用swing設計,先上圖看一下:

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

界面比較簡陋,相比于其他的生成工具,這個ui界面傾向于自己去配置多表查詢的sql,更加的靈活,第一部配置設定制關聯表語句,第二部配置設定置查詢語句,也就是select的字段,第三部配置設定置條件資訊,也就是where後面的内容,相信大家一看就會明白。源碼挺長的,沒有做什麼優化,如下:

package codeMaker;

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;

import constant.ChildWindowConstant;
import constant.CodeConstant;
import constant.CompareComboBox;
import constant.FiledComment;
import constant.Filed_cn;
import constant.Filed_eng;
import constant.OrderComboBox;
import constant.RelationJcombox;
import constant.ServiceTypeComboBox;
import constant.Table1;
import constant.Table1Fileds;
import constant.Table2;
import constant.Table2Fileds;
import entity.Parameters;
import entity.TableConditionModel;
import entity.TableFiledModel;
import entity.TableRelationModel;
import entity.TablesQueryModel;

public class TablesQuery {

	private static String currentDataBaseName;
	private static String currentDataBaseUrl;
	private JFrame frame;
	private JTextField currentModelName;
	private JTextField currentModelName_cn;

	public JFrame getFrame() {
		return frame;
	}

	public void setFrame(JFrame frame) {
		this.frame = frame;
	}

	/**
	 * Launch the application.
	 */
	public static void main(final Parameters parameters) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {

					if (currentDataBaseName == null || currentDataBaseUrl == null) {
						// 記錄目前資料庫的名稱和url
						currentDataBaseName = parameters.getDataBaseNameVal();
						currentDataBaseUrl = parameters.getDataBaseUrl();
					} else {
						// 如果資料庫不一緻,清空map
						if (!currentDataBaseName.equals(parameters.getDataBaseNameVal())
								|| !currentDataBaseUrl.equals(parameters.getDataBaseUrl())) {
							ChildWindowConstant.tablesQueryMap.clear();
							ChildWindowConstant.tablesQueryEndAndCnMap.clear();
						}

					}

					TablesQuery window = new TablesQuery();
					ChildWindowConstant.tablesQuery = window;
					window.frame.setVisible(true);

					JOptionPane.showMessageDialog(window.frame,
							"表1字段、表2字段:多個字段使用 & 隔開,字段個數保持一緻" + CodeConstant.NEW_LINE + "類型描述:" + CodeConstant.NEW_LINE
									+ "    布爾示例:是#否 其中是和否填寫資料庫中用來表示是和否的值" + CodeConstant.NEW_LINE
									+ "    狀态碼示例:狀态名稱&狀态值#狀态名稱&狀态值(填寫狀态名稱和狀态值便于前台生成樣式)" + CodeConstant.NEW_LINE
									+ "    其他類型将根據類型生成對應的樣式,無需描述" + CodeConstant.NEW_LINE + "注意:關聯表資訊配置完點選确定才會生效!!!",
							"提示", JOptionPane.INFORMATION_MESSAGE);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * test
	 * 
	 * @param parameters
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {

					TablesQuery window = new TablesQuery();
					ChildWindowConstant.tablesQuery = window;
					window.frame.setVisible(true);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public TablesQuery() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setResizable(false);
		frame.setIconImage(Toolkit.getDefaultToolkit().getImage(TablesQuery.class
				.getResource("/org/pushingpixels/substance/internal/contrib/randelshofer/quaqua/images/palette.png")));
		frame.setTitle("多表查詢配置");
		frame.setBounds(100, 100, 1281, 759);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

		JScrollPane addTableScrollPane = new JScrollPane();

		JScrollPane queryScrollPane = new JScrollPane();

		JButton addTable = new JButton("添加關聯表資訊");

		JButton addQuery = new JButton("添加查詢字段");

		JLabel label = new JLabel("目前子產品英文名稱");

		currentModelName = new JTextField();
		currentModelName.setColumns(10);

		JButton confirm = new JButton("确定");

		JLabel label_1 = new JLabel("檢視已配置子產品");

		JButton addCondition = new JButton("添加條件字段");

		addQuery.setEnabled(false);
		addCondition.setEnabled(false);

		JScrollPane conditionScrollPane = new JScrollPane();

		JLabel label_2 = new JLabel("*");
		label_2.setForeground(Color.RED);

		JButton restart = new JButton("清空重配");

		JComboBox<String> tableConfigExit = new JComboBox<String>();

		String[] modelArr = ChildWindowConstant.tablesQueryMap.keySet().toArray(new String[] {});

		tableConfigExit.setModel(new DefaultComboBoxModel<>(new String[] { "--請選擇--" }));

		for (String model : modelArr) {
			tableConfigExit.addItem(model);
		}

		JButton confirmRelTable = new JButton("确定");
		JLabel label_3 = new JLabel("——————》");

		JLabel cnLable = new JLabel("中文名稱");

		currentModelName_cn = new JTextField();
		currentModelName_cn.setColumns(10);

		JLabel label_4 = new JLabel("*");
		label_4.setForeground(Color.RED);

		JButton button = new JButton("配置說明");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				JOptionPane.showMessageDialog(frame,
						"表1字段、表2字段:多個字段使用 & 隔開,字段個數保持一緻" + CodeConstant.NEW_LINE + "類型描述:" + CodeConstant.NEW_LINE
								+ "    布爾示例:是#否 其中是和否填寫資料庫中用來表示是和否的值" + CodeConstant.NEW_LINE
								+ "    狀态碼示例:狀态名稱&狀态值#狀态名稱&狀态值(填寫狀态名稱和狀态值便于前台生成樣式)" + CodeConstant.NEW_LINE
								+ "    其他類型将根據類型生成對應的樣式,無需描述" + CodeConstant.NEW_LINE + "注意:關聯表資訊配置完點選确定才會生效!!!",
						"提示", JOptionPane.INFORMATION_MESSAGE);

			}
		});
		GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
		groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
				.createSequentialGroup().addGap(25).addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(
								groupLayout.createSequentialGroup()
										.addComponent(conditionScrollPane, GroupLayout.DEFAULT_SIZE, 1240,
												Short.MAX_VALUE)
										.addContainerGap())
						.addGroup(groupLayout.createSequentialGroup()
								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING).addComponent(addCondition)
										.addComponent(addQuery).addComponent(addTable)
										.addGroup(groupLayout.createSequentialGroup().addComponent(label)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(currentModelName, GroupLayout.PREFERRED_SIZE, 91,
														GroupLayout.PREFERRED_SIZE)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(label_2, GroupLayout.PREFERRED_SIZE, 6,
														GroupLayout.PREFERRED_SIZE)
												.addGap(18).addComponent(cnLable)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(currentModelName_cn, GroupLayout.PREFERRED_SIZE, 98,
														GroupLayout.PREFERRED_SIZE)
												.addPreferredGap(ComponentPlacement.RELATED).addComponent(label_4)
												.addGap(26).addComponent(label_1)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(
														tableConfigExit, GroupLayout.PREFERRED_SIZE, 102,
														GroupLayout.PREFERRED_SIZE))
										.addGroup(groupLayout.createSequentialGroup().addGroup(groupLayout
												.createParallelGroup(Alignment.LEADING)
												.addGroup(groupLayout.createSequentialGroup().addComponent(button)
														.addGap(18).addComponent(restart).addGap(18)
														.addComponent(confirm))
												.addGroup(groupLayout.createSequentialGroup()
														.addPreferredGap(ComponentPlacement.RELATED)
														.addComponent(addTableScrollPane, GroupLayout.DEFAULT_SIZE,
																1026, Short.MAX_VALUE))
												.addComponent(queryScrollPane, GroupLayout.DEFAULT_SIZE, 1026,
														Short.MAX_VALUE))
												.addPreferredGap(ComponentPlacement.UNRELATED).addComponent(label_3)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(confirmRelTable)))
								.addContainerGap(30, GroupLayout.PREFERRED_SIZE)))));
		groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(groupLayout
				.createSequentialGroup()
				.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup().addContainerGap(210, Short.MAX_VALUE)
								.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label_3)
										.addComponent(confirmRelTable))
								.addGap(266))
						.addGroup(groupLayout.createSequentialGroup().addGap(30)
								.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(label)
										.addComponent(currentModelName, GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
										.addComponent(label_2).addComponent(cnLable)
										.addComponent(currentModelName_cn, GroupLayout.PREFERRED_SIZE,
												GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
										.addComponent(label_4).addComponent(label_1).addComponent(tableConfigExit,
												GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
												GroupLayout.PREFERRED_SIZE))
								.addGap(18).addComponent(addTable).addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(addTableScrollPane, GroupLayout.PREFERRED_SIZE, 138,
										GroupLayout.PREFERRED_SIZE)
								.addGap(22).addComponent(addQuery).addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(queryScrollPane, GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)))
				.addGap(18).addComponent(addCondition).addPreferredGap(ComponentPlacement.RELATED)
				.addComponent(conditionScrollPane, GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)
				.addPreferredGap(ComponentPlacement.RELATED)
				.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE).addComponent(confirm)
						.addComponent(restart).addComponent(button))
				.addGap(30)));

		JPanel conditionPanel = new JPanel();
		conditionScrollPane.setViewportView(conditionPanel);

		JPanel querysPanel = new JPanel();
		queryScrollPane.setViewportView(querysPanel);

		JPanel tablesPanel = new JPanel();
		addTableScrollPane.setViewportView(tablesPanel);

		tablesPanel.setLayout(new GridLayout(0, 5, 5, 5));
		querysPanel.setLayout(new GridLayout(0, 6, 5, 5));
		conditionPanel.setLayout(new GridLayout(0, 8, 5, 5));

		String[] tablesArr = new String[] { "關聯關系", "表1", "表2", "表1字段", "表2字段" };
		String[] querysArr = new String[] { "表名", "字段", "中文名稱", "字段類型", "類型描述", "是否可排序" };
		String[] conditionsArr = new String[] { "關聯關系", "表名", "字段", "中文名稱", "字段類型", "類型描述", "比較關系", "固定值" };

		List<TableRelationModel> tableRelationModelLists = new ArrayList<TableRelationModel>();
		Map<String, String> tableMap = new HashMap<>();

		addTable.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				addQuery.setEnabled(false);
				addCondition.setEnabled(false);

				if (tablesPanel.getComponentCount() == 0) {
					for (String tableStr : tablesArr) {
						JLabel label = new JLabel(tableStr);
						tablesPanel.add(label);
					}
					addTableMethod(tablesPanel);
					((Table2) tablesPanel.getComponent(7)).setEnabled(false);
					((Table1Fileds) tablesPanel.getComponent(8)).setEnabled(false);
					((Table1Fileds) tablesPanel.getComponent(8)).setText("/");
					((Table2Fileds) tablesPanel.getComponent(9)).setEnabled(false);
					((Table2Fileds) tablesPanel.getComponent(9)).setText("/");
				} else {
					addTableMethod(tablesPanel);
				}

				frame.validate();
				frame.repaint();

			}

			private void addTableMethod(JPanel tablesPanel) {

				List<String> table2List = new ArrayList<>();

				if (tablesPanel.getComponentCount() >= 5) {

					Component[] components = tablesPanel.getComponents();

					for (int i = 5; i < components.length; i++) {

						if ("Table1".equals(components[i].getClass().getSimpleName())) {

							Table1 table1 = (Table1) components[i];

							if ("".equals(table1.getText())) {
								JOptionPane.showMessageDialog(frame, "請先把目前内容填寫完畢再增加關聯表資訊!", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return;
							}

							table2List.add(table1.getText());
						}

						else if ("Table1Fileds".equals(components[i].getClass().getSimpleName())) {

							Table1Fileds table1Fileds = (Table1Fileds) components[i];

							if ("".equals(table1Fileds.getText())) {
								JOptionPane.showMessageDialog(frame, "請先把目前内容填寫完畢再增加關聯表資訊!", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return;
							}
						}

						else if ("Table2Fileds".equals(components[i].getClass().getSimpleName())) {

							Table2Fileds table2Fileds = (Table2Fileds) components[i];

							if ("".equals(table2Fileds.getText())) {
								JOptionPane.showMessageDialog(frame, "請先把目前内容填寫完畢再增加關聯表資訊!", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return;
							}
						}

					}
				}

				JComboBox<String> relationComBox = null;
				// 如果是第一次添加
				if (tablesPanel.getComponentCount() == 5) {
					// 關聯關系
					relationComBox = new JComboBox<>(new String[] { "from" });
				} else {
					// 關聯關系
					relationComBox = new JComboBox<>(new String[] { "left join", "join", "right join" });
				}

				// 關聯表
				Table1 table1 = new Table1();
				// 關聯字段
				Table2 table2 = new Table2();

				if (tablesPanel.getComponentCount() >= 10) {
					table2.setModel(new DefaultComboBoxModel<>(table2List.toArray(new String[] {})));
				}

				Table1Fileds table1Fileds = new Table1Fileds();
				Table2Fileds table2Fileds = new Table2Fileds();

				tablesPanel.add(relationComBox);
				tablesPanel.add(table1);
				tablesPanel.add(table2);
				tablesPanel.add(table1Fileds);
				tablesPanel.add(table2Fileds);
			}
		});

		addQuery.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if (!canAddQuery(querysPanel)) {
					return;
				}

				if (querysPanel.getComponentCount() == 0) {
					for (String queryStr : querysArr) {
						JLabel label = new JLabel(queryStr);
						querysPanel.add(label);
					}
					addQueryMethod(querysPanel);
				} else {
					addQueryMethod(querysPanel);
				}

				frame.validate();
				frame.repaint();
			}

			private boolean canAddQuery(JPanel querysPanel) {

				if (querysPanel.getComponentCount() >= 10) {

					Component[] components = querysPanel.getComponents();
					for (int i = 6; i < components.length; i++) {

						if ("Filed_eng".equals(components[i].getClass().getSimpleName())) {

							Filed_eng filed_eng = (Filed_eng) components[i];

							if ("".equals(filed_eng.getText())) {
								JOptionPane.showMessageDialog(frame, "請先把目前内容填寫完畢再增加查詢字段資訊!", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						}

						else if ("Filed_cn".equals(components[i].getClass().getSimpleName())) {

							Filed_cn filed_cn = (Filed_cn) components[i];

							if ("".equals(filed_cn.getText())) {
								JOptionPane.showMessageDialog(frame, "請先把目前内容填寫完畢再增加查詢字段資訊!", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						}

						else if ("ServiceTypeComboBox".equals(components[i].getClass().getSimpleName())) {

							@SuppressWarnings("unchecked")
							ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) components[i];

							if ("布爾".equals(serviceTypeComboBox.getSelectedItem())
									|| "狀态碼".equals(serviceTypeComboBox.getSelectedItem())) {

								FiledComment filedComment = (FiledComment) components[i + 1];

								if ("".equals(filedComment.getText())) {

									JOptionPane.showMessageDialog(frame, "布爾或狀态碼的類型描述不能為空!!詳細請見配置說明!", "提示",
											JOptionPane.INFORMATION_MESSAGE);
									return false;
								}

							}
						}

					}

				}

				return true;
			}

			private void addQueryMethod(JPanel querysPanel) {

				Set<String> tables = tableMap.keySet();
				String[] tableArr = tables.toArray(new String[] {});

				// 表名
				JComboBox<String> tableName = new JComboBox<>(tableArr);

				// 字段
				JTextField tableFiled = new Filed_eng();

				// 中文名稱
				JTextField tableFiled_cn = new Filed_cn();

				// 字段類型
				JComboBox<String> filedType = new ServiceTypeComboBox<>();

				String[] typeList = new String[] { "字元串", "數字", "布爾", "狀态碼", "日期", "文字域" };

				filedType.setModel(new DefaultComboBoxModel<String>(typeList));

				// 類型描述
				JTextField filedComment = new FiledComment();

				// 是否可排序
				JComboBox<String> comboBox = new OrderComboBox<String>();
				comboBox.setModel(new DefaultComboBoxModel<String>(new String[] { "否", "是" }));

				querysPanel.add(tableName);
				querysPanel.add(tableFiled);
				querysPanel.add(tableFiled_cn);
				querysPanel.add(filedType);
				querysPanel.add(filedComment);
				querysPanel.add(comboBox);
			}

		});

		addCondition.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if (!canAddCondition(conditionPanel)) {
					return;
				}

				if (conditionPanel.getComponentCount() == 0) {
					for (String conditionArr : conditionsArr) {
						JLabel label = new JLabel(conditionArr);
						conditionPanel.add(label);
					}
					addConditionMethod(conditionPanel);
					conditionPanel.getComponent(8).setVisible(false);
				} else {
					addConditionMethod(conditionPanel);
				}

				frame.validate();
				frame.repaint();
			}

			private boolean canAddCondition(JPanel conditionPanel) {

				if (conditionPanel.getComponentCount() >= 16) {

					Component[] components = conditionPanel.getComponents();

					for (int i = 8; i < components.length; i++) {

						if ("Filed_eng".equals(components[i].getClass().getSimpleName())) {

							Filed_eng filed_eng = (Filed_eng) components[i];

							if ("".equals(filed_eng.getText())) {
								JOptionPane.showMessageDialog(frame, "請先把目前内容填寫完畢再增加查詢字段資訊!", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						}

						else if ("Filed_cn".equals(components[i].getClass().getSimpleName())) {

							Filed_cn filed_cn = (Filed_cn) components[i];

							if ("".equals(filed_cn.getText())) {
								JOptionPane.showMessageDialog(frame, "請先把目前内容填寫完畢再增加查詢字段資訊!", "提示",
										JOptionPane.INFORMATION_MESSAGE);
								return false;
							}
						}

						else if ("ServiceTypeComboBox".equals(components[i].getClass().getSimpleName())) {

							@SuppressWarnings("unchecked")
							ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) components[i];

							if ("布爾".equals(serviceTypeComboBox.getSelectedItem())
									|| "狀态碼".equals(serviceTypeComboBox.getSelectedItem())) {

								FiledComment filedComment = (FiledComment) components[i + 1];

								if ("".equals(filedComment.getText())) {

									JOptionPane.showMessageDialog(frame, "布爾或狀态碼的類型描述不能為空!!詳細請見配置說明!", "提示",
											JOptionPane.INFORMATION_MESSAGE);
									return false;
								}

							}
						}

					}
				}

				return true;
			}

			private void addConditionMethod(JPanel conditionsPanel) {

				// 關聯關系
				JComboBox<String> relationComBox = new RelationJcombox<>();

				relationComBox.setModel(new DefaultComboBoxModel<>(new String[] { "and", "or" }));

				// 表名
				Set<String> tables = tableMap.keySet();
				String[] tableArr = tables.toArray(new String[] {});
				JComboBox<String> tableName = new JComboBox<>(tableArr);

				// 字段
				JTextField tableFiled = new Filed_eng();

				// 中文名稱
				JTextField tableFiled_cn = new Filed_cn();

				// 字段類型
				JComboBox<String> filedType = new ServiceTypeComboBox<>();

				String[] typeList = new String[] { "字元串", "數字", "布爾", "狀态碼", "日期", "文字域" };

				filedType.setModel(new DefaultComboBoxModel<String>(typeList));

				FiledComment filedComment = new FiledComment();

				// 比較關系
				JComboBox<String> compareRelation = new CompareComboBox<>();

				compareRelation.setModel(
						new DefaultComboBoxModel<>(new String[] { "=", "like", ">=", "<=", "!=", ">= && <=" }));

				// 固定值
				JTextField unchangeValue = new JTextField();

				conditionsPanel.add(relationComBox);
				conditionsPanel.add(tableName);
				conditionsPanel.add(tableFiled);
				conditionsPanel.add(tableFiled_cn);
				conditionsPanel.add(filedType);
				conditionsPanel.add(filedComment);
				conditionsPanel.add(compareRelation);
				conditionsPanel.add(unchangeValue);
			}
		});

		restart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				tablesPanel.removeAll();
				querysPanel.removeAll();
				conditionPanel.removeAll();

				frame.validate();
				frame.repaint();

			}
		});

		confirm.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				String modelName = currentModelName.getText();

				String modelNameCn = currentModelName_cn.getText();

				if ("".equals(modelName) || "".equals(modelNameCn)) {
					JOptionPane.showMessageDialog(frame, "中文和英文子產品名稱不可以為空!請填寫!", "錯誤", JOptionPane.ERROR_MESSAGE);
					return;
				}

				if (!checkRelTable(tablesPanel, tableRelationModelLists, tableMap)) {
					return;
				}

				String selectTableSql = "";

				for (int i = 0; i < tableRelationModelLists.size(); i++) {

					TableRelationModel tableRelationModel = tableRelationModelLists.get(i);

					// 如果是第一個
					String anotherTableName = tableRelationModel.getAnotherTableName();

					String table2Text = tableRelationModel.getTable2_text();

					if (i == 0) {

						selectTableSql += " " + tableRelationModel.getRelation() + " "
								+ tableRelationModel.getTable1_text() + " " + anotherTableName + " ";
						continue;
					}

					selectTableSql += " " + tableRelationModel.getRelation() + " " + tableRelationModel.getTable1_text()
							+ " " + anotherTableName + " ON ";

					String table1Fileds = tableRelationModel.getTable1Fileds_text();
					String table2Fileds = tableRelationModel.getTable2Fileds_text();

					String[] table1FiledsArr = table1Fileds.split("&");
					String[] table2FiledsArr = table2Fileds.split("&");

					if (table1FiledsArr.length != table2FiledsArr.length) {
						JOptionPane.showMessageDialog(frame, "關聯表配置中第  " + (i + 1) + " 行表1和表2的關聯字段的個數不相等,請檢查後重新配置!",
								"錯誤", JOptionPane.ERROR_MESSAGE);
						return;
					}

					for (int j = 0; j < table1FiledsArr.length; j++) {

						if (j == table1FiledsArr.length - 1) {
							selectTableSql += anotherTableName + "." + table1FiledsArr[j] + " = "
									+ tableMap.get(table2Text) + "." + table2FiledsArr[j];
							break;
						}

						selectTableSql += anotherTableName + "." + table1FiledsArr[j] + " = " + tableMap.get(table2Text)
								+ "." + table2FiledsArr[j] + " and ";

					}

				}

				System.out.println(selectTableSql);

				Component[] queryComponents = querysPanel.getComponents();
				List<TableFiledModel> tableFiledModels = new ArrayList<>();
				// 查詢panel的資訊
				for (int i = 6; i < queryComponents.length; i++) {

					if ("JComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						JComboBox<String> comboBox = (JComboBox<String>) queryComponents[i];

						TableFiledModel filedModel = new TableFiledModel();

						filedModel.setComboBox(comboBox);

						filedModel.setTableName((String) comboBox.getSelectedItem());

						filedModel.setAnotherTableName(tableMap.get((String) comboBox.getSelectedItem()));

						tableFiledModels.add(filedModel);
					}

					else if ("Filed_eng".equals(queryComponents[i].getClass().getSimpleName())) {
						Filed_eng filed_eng = (Filed_eng) queryComponents[i];

						String engFiled = filed_eng.getText();

						if ("".equals(engFiled)) {
							JOptionPane.showMessageDialog(frame, "添加查詢字段中的字段列不能為空!請填寫!!", "錯誤",
									JOptionPane.ERROR_MESSAGE);
							return;
						}

						TableFiledModel tableFiledModel = tableFiledModels.get(tableFiledModels.size() - 1);

						tableFiledModel.setFiled_eng(filed_eng);
						tableFiledModel.setFiledText_eng(engFiled);
						tableFiledModel.setAnotherFiledName(tableFiledModel.getAnotherTableName() + "_" + engFiled);
					}

					else if ("Filed_cn".equals(queryComponents[i].getClass().getSimpleName())) {

						Filed_cn filed_cn = (Filed_cn) queryComponents[i];

						String cnFiled = filed_cn.getText();

						if ("".equals(cnFiled)) {
							JOptionPane.showMessageDialog(frame, "添加查詢字段中的中文名稱列不能為空!請填寫!!", "錯誤",
									JOptionPane.ERROR_MESSAGE);
							return;
						}

						tableFiledModels.get(tableFiledModels.size() - 1).setFiled_cn(filed_cn);
						tableFiledModels.get(tableFiledModels.size() - 1).setFiledText_cn(cnFiled);
					}

					else if ("ServiceTypeComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) queryComponents[i];

						String filedType = (String) serviceTypeComboBox.getSelectedItem();

						tableFiledModels.get(tableFiledModels.size() - 1).setServiceTypeComboBox(serviceTypeComboBox);
						tableFiledModels.get(tableFiledModels.size() - 1).setFiledType(filedType);

					}

					else if ("FiledComment".equals(queryComponents[i].getClass().getSimpleName())) {

						FiledComment filedComment = (FiledComment) queryComponents[i];

						String comment = filedComment.getText();

						String[] serviceArr = comment.split("#");

						TableFiledModel tableFiledModel = tableFiledModels.get(tableFiledModels.size() - 1);

						tableFiledModel.setTextFiled(filedComment);
						tableFiledModel.setFiledCommentStr(comment);

						String filedType = tableFiledModel.getFiledType();

						Map<String, Object> map = new HashMap<>();
						if ("布爾".equals(filedType)) {
							try {
								map.put("是", serviceArr[0]);
								map.put("否", serviceArr[1]);
								tableFiledModel.setFiledComment(map);
							} catch (Exception e1) {
								JOptionPane.showMessageDialog(frame, "布爾值的類型描述填寫有誤,請檢查重寫!", "錯誤",
										JOptionPane.ERROR_MESSAGE);
								return;
							}
						}

						if ("狀态碼".equals(filedType)) {
							try {
								for (String serviece : serviceArr) {
									String[] arr = serviece.split("&");
									map.put(arr[0], arr[1]);
								}
								tableFiledModel.setFiledComment(map);
							} catch (Exception e1) {
								JOptionPane.showMessageDialog(frame, "狀态碼的類型描述填寫有誤,請檢查重寫!", "錯誤",
										JOptionPane.ERROR_MESSAGE);
								return;
							}
						}
					}

					else if ("OrderComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						OrderComboBox<String> orderComboBox = (OrderComboBox<String>) queryComponents[i];

						String canSort = (String) orderComboBox.getSelectedItem();

						tableFiledModels.get(tableFiledModels.size() - 1).setOrderComboBox(orderComboBox);

						tableFiledModels.get(tableFiledModels.size() - 1).setCanSort(canSort);

					}

				}

				if (tableFiledModels.size() == 0) {
					JOptionPane.showMessageDialog(frame, "請配置查詢字段資訊!", "錯誤", JOptionPane.ERROR_MESSAGE);
					return;
				}

				Component[] conditionComponents = conditionPanel.getComponents();

				List<TableConditionModel> tableConditionModels = new ArrayList<>();
				// 查詢panel的資訊
				for (int i = 6; i < conditionComponents.length; i++) {

					if ("RelationJcombox".equals(conditionComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						RelationJcombox<String> comboBox = (RelationJcombox<String>) conditionComponents[i];

						TableConditionModel conditionModel = new TableConditionModel();

						conditionModel.setRelationJcombox(comboBox);
						conditionModel.setRelation((String) comboBox.getSelectedItem());

						tableConditionModels.add(conditionModel);

					}

					else if ("JComboBox".equals(conditionComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						JComboBox<String> comboBox = (JComboBox<String>) conditionComponents[i];

						tableConditionModels.get(tableConditionModels.size() - 1).setComboBox(comboBox);
						// 設定表名
						tableConditionModels.get(tableConditionModels.size() - 1)
								.setTableName((String) comboBox.getSelectedItem());

						// 設定表别名
						tableConditionModels.get(tableConditionModels.size() - 1)
								.setAnotherTableName(tableMap.get((String) comboBox.getSelectedItem()));
					}

					else if ("Filed_eng".equals(conditionComponents[i].getClass().getSimpleName())) {
						Filed_eng filed_eng = (Filed_eng) conditionComponents[i];

						String engFiled = filed_eng.getText();

						if ("".equals(engFiled)) {
							JOptionPane.showMessageDialog(frame, "添加條件字段中的字段列不能為空!請填寫!!", "錯誤",
									JOptionPane.ERROR_MESSAGE);
							return;
						}

						tableConditionModels.get(tableConditionModels.size() - 1).setFiled_eng_textFiled(filed_eng);
						tableConditionModels.get(tableConditionModels.size() - 1).setFiled_eng(engFiled);
					}

					else if ("Filed_cn".equals(conditionComponents[i].getClass().getSimpleName())) {

						Filed_cn filed_cn = (Filed_cn) conditionComponents[i];

						String cnFiled = filed_cn.getText();

						if ("".equals(cnFiled)) {
							JOptionPane.showMessageDialog(frame, "添加條件字段中的中文名稱列不能為空!請填寫!!", "錯誤",
									JOptionPane.ERROR_MESSAGE);
							return;
						}

						tableConditionModels.get(tableConditionModels.size() - 1).setFiled_cn_textFiled(filed_cn);
						tableConditionModels.get(tableConditionModels.size() - 1).setFiled_cn(cnFiled);
					}

					else if ("ServiceTypeComboBox".equals(conditionComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						ServiceTypeComboBox<String> serviceTypeComboBox = (ServiceTypeComboBox<String>) conditionComponents[i];

						String filedType = (String) serviceTypeComboBox.getSelectedItem();

						tableConditionModels.get(tableConditionModels.size() - 1)
								.setServiceTypeComboBox(serviceTypeComboBox);
						tableConditionModels.get(tableConditionModels.size() - 1).setServiceType(filedType);

					}

					else if ("FiledComment".equals(conditionComponents[i].getClass().getSimpleName())) {

						FiledComment filedComment = (FiledComment) conditionComponents[i];

						String comment = filedComment.getText();

						String[] serviceArr = comment.split("#");

						TableConditionModel tableConditionModel = tableConditionModels
								.get(tableConditionModels.size() - 1);

						tableConditionModel.setFiledComment(filedComment);

						String filedType = tableConditionModel.getServiceType();

						Map<String, Object> map = new HashMap<>();
						if ("布爾".equals(filedType)) {
							try {
								map.put("是", serviceArr[0]);
								map.put("否", serviceArr[1]);
								tableConditionModel.setServiceText(map);
							} catch (Exception e1) {
								JOptionPane.showMessageDialog(frame, "布爾值的類型描述填寫有誤,請檢查重寫!", "錯誤",
										JOptionPane.ERROR_MESSAGE);
								return;
							}
						}

						if ("狀态碼".equals(filedType)) {
							try {
								for (String serviece : serviceArr) {
									String[] arr = serviece.split("&");
									map.put(arr[0], arr[1]);
								}
								tableConditionModel.setServiceText(map);
							} catch (Exception e1) {
								JOptionPane.showMessageDialog(frame, "狀态碼的類型描述填寫有誤,請檢查重寫!", "錯誤",
										JOptionPane.ERROR_MESSAGE);
								return;
							}
						}
					}

					else if ("CompareComboBox".equals(conditionComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						CompareComboBox<String> compareComboBox = (CompareComboBox<String>) conditionComponents[i];

						String compareText = (String) compareComboBox.getSelectedItem();

						tableConditionModels.get(tableConditionModels.size() - 1).setCompareComboBox(compareComboBox);
						tableConditionModels.get(tableConditionModels.size() - 1).setCompareText(compareText);

					}

					else if ("JTextField".equals(conditionComponents[i].getClass().getSimpleName())) {

						JTextField textField = (JTextField) conditionComponents[i];

						String unchangeValue = textField.getText();

						tableConditionModels.get(tableConditionModels.size() - 1).setTextFiled(textField);
						tableConditionModels.get(tableConditionModels.size() - 1).setUnchangeValue(unchangeValue);

					}

				}

				if (tableConditionModels.size() == 0) {
					JOptionPane.showMessageDialog(frame, "請配置條件字段資訊!", "錯誤", JOptionPane.ERROR_MESSAGE);
					return;
				}


				TablesQueryModel tablesQueryModel = new TablesQueryModel();

				// 儲存多表查詢的資訊配置
				tablesQueryModel.setFormSql(selectTableSql);
				List<TableRelationModel> realTableRelationModelLists = new ArrayList<>();
				realTableRelationModelLists.addAll(tableRelationModelLists);
				tablesQueryModel.setTableRelationModelLists(realTableRelationModelLists);
				tablesQueryModel.setTableFiledModels(tableFiledModels);
				tablesQueryModel.setTableConditionModels(tableConditionModels);

				if (ChildWindowConstant.tablesQueryMap.containsKey(modelName)) {
					int getCodeConfirmDialog = JOptionPane.showConfirmDialog(frame,
							"目前子產品名稱‘" + modelName + "’已存在,确認覆寫?", "提示", JOptionPane.YES_NO_OPTION);

					if (getCodeConfirmDialog != 0) {
						return;
					}
				}

				ChildWindowConstant.tablesQueryMap.put(modelName, tablesQueryModel);
				ChildWindowConstant.tablesQueryEndAndCnMap.put(modelName, modelNameCn);

				JOptionPane.showMessageDialog(frame, "目前子產品配置成功!", "提示", JOptionPane.INFORMATION_MESSAGE);

				String[] modelArr = ChildWindowConstant.tablesQueryMap.keySet().toArray(new String[] {});

				tableConfigExit.setModel(new DefaultComboBoxModel<>(new String[] { "--請選擇--" }));

				for (String model : modelArr) {
					tableConfigExit.addItem(model);
				}

				tablesPanel.removeAll();
				querysPanel.removeAll();
				conditionPanel.removeAll();

				frame.validate();
				frame.repaint();

			}
		});

		confirmRelTable.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if (!checkRelTable(tablesPanel, tableRelationModelLists, tableMap)) {
					return;
				}

				addQuery.setEnabled(true);
				addCondition.setEnabled(true);

				Component[] queryComponents = querysPanel.getComponents();

				for (int i = 6; i < queryComponents.length; i++) {

					if ("JComboBox".equals(queryComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						JComboBox<String> comboBox = (JComboBox<String>) queryComponents[i];

						Set<String> tables = tableMap.keySet();

						comboBox.removeAllItems();

						for (String table : tables) {
							comboBox.addItem(table);
						}

					}
				}

				Component[] conditionComponents = conditionPanel.getComponents();

				for (int i = 8; i < conditionComponents.length; i++) {

					if ("JComboBox".equals(conditionComponents[i].getClass().getSimpleName())) {

						@SuppressWarnings("unchecked")
						JComboBox<String> comboBox = (JComboBox<String>) conditionComponents[i];

						Set<String> tables = tableMap.keySet();

						comboBox.removeAllItems();

						for (String table : tables) {
							comboBox.addItem(table);
						}

					}
				}

				frame.validate();
				frame.repaint();

			}
		});

		tableConfigExit.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {

				if (e.getStateChange() != 1) {
					return;
				}

				// 選取的目前子產品
				String currentModel = tableConfigExit.getSelectedItem().toString();

				if ("--請選擇--".equals(currentModel)) {

					tablesPanel.removeAll();
					querysPanel.removeAll();
					conditionPanel.removeAll();

					currentModelName.setText("");
					currentModelName_cn.setText("");

					frame.validate();
					frame.repaint();

					return;

				}

				currentModelName.setText(currentModel);

				String currentCnModelName = ChildWindowConstant.tablesQueryEndAndCnMap.get(currentModel);

				currentModelName_cn.setText(currentCnModelName);

				TablesQueryModel tablesQueryModel = ChildWindowConstant.tablesQueryMap.get(currentModel);

				List<TableRelationModel> tableRelations = tablesQueryModel.getTableRelationModelLists();

				List<TableFiledModel> tableFileds = tablesQueryModel.getTableFiledModels();

				List<TableConditionModel> tableConditions = tablesQueryModel.getTableConditionModels();

				// 移除三個panel所有的元件
				tablesPanel.removeAll();
				querysPanel.removeAll();
				conditionPanel.removeAll();

				// 加入表頭和内容
				for (String tableStr : tablesArr) {
					JLabel label = new JLabel(tableStr);
					tablesPanel.add(label);
				}
				for (TableRelationModel tableRelation : tableRelations) {

					tablesPanel.add(tableRelation.getComboBox());
					tablesPanel.add(tableRelation.getTable1());
					tablesPanel.add(tableRelation.getTable2());
					tablesPanel.add(tableRelation.getTable1Fileds());
					tablesPanel.add(tableRelation.getTable2Fileds());

				}

				for (String queryStr : querysArr) {
					JLabel label = new JLabel(queryStr);
					querysPanel.add(label);
				}
				for (TableFiledModel tableFiled : tableFileds) {

					querysPanel.add(tableFiled.getComboBox());
					querysPanel.add(tableFiled.getFiled_eng());
					querysPanel.add(tableFiled.getFiled_cn());
					querysPanel.add(tableFiled.getServiceTypeComboBox());
					querysPanel.add(tableFiled.getTextFiled());
					querysPanel.add(tableFiled.getOrderComboBox());

				}

				for (String conditionStr : conditionsArr) {
					JLabel label = new JLabel(conditionStr);
					conditionPanel.add(label);
				}
				for (TableConditionModel tableCondition : tableConditions) {

					conditionPanel.add(tableCondition.getRelationJcombox());
					conditionPanel.add(tableCondition.getComboBox());
					conditionPanel.add(tableCondition.getFiled_eng_textFiled());
					conditionPanel.add(tableCondition.getFiled_cn_textFiled());
					conditionPanel.add(tableCondition.getServiceTypeComboBox());
					conditionPanel.add(tableCondition.getFiledComment());
					conditionPanel.add(tableCondition.getCompareComboBox());
					conditionPanel.add(tableCondition.getTextFiled());

				}

				frame.validate();
				frame.repaint();

			}

		});

		frame.getContentPane().setLayout(groupLayout);
	}

	private boolean checkRelTable(JPanel tablesPanel, List<TableRelationModel> tableRelationModelLists,
			Map<String, String> tableMap) {

		// 清空集合
		tableRelationModelLists.clear();
		tableMap.clear();

		Component[] tableComponents = tablesPanel.getComponents();

		// 讀取關聯表的配置資訊
		for (int i = 4; i < tableComponents.length; i++) {

			if ("JComboBox".equals(tableComponents[i].getClass().getSimpleName())) {

				@SuppressWarnings("unchecked")
				JComboBox<String> comboBox = (JComboBox<String>) tableComponents[i];

				TableRelationModel tableRelationModel = new TableRelationModel();

				tableRelationModel.setComboBox(comboBox);

				tableRelationModel.setRelation((String) comboBox.getSelectedItem());

				tableRelationModelLists.add(tableRelationModel);

			}

			else if ("Table1".equals(tableComponents[i].getClass().getSimpleName())) {
				Table1 table1 = (Table1) tableComponents[i];

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable1(table1);

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable1_text(table1.getText());

				// 表别名
				tableRelationModelLists.get(tableRelationModelLists.size() - 1)
						.setAnotherTableName("T" + (tableRelationModelLists.size() - 1));

			}

			else if ("Table2".equals(tableComponents[i].getClass().getSimpleName())) {

				Table2 table2 = (Table2) tableComponents[i];

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable2(table2);

				tableRelationModelLists.get(tableRelationModelLists.size() - 1)
						.setTable2_text((String) table2.getSelectedItem());

			}

			else if ("Table1Fileds".equals(tableComponents[i].getClass().getSimpleName())) {

				Table1Fileds table1Fileds = (Table1Fileds) tableComponents[i];

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable1Fileds(table1Fileds);

				tableRelationModelLists.get(tableRelationModelLists.size() - 1)
						.setTable1Fileds_text(table1Fileds.getText());

			}

			else if ("Table2Fileds".equals(tableComponents[i].getClass().getSimpleName())) {

				Table2Fileds table2Fileds = (Table2Fileds) tableComponents[i];

				tableRelationModelLists.get(tableRelationModelLists.size() - 1).setTable2Fileds(table2Fileds);

				tableRelationModelLists.get(tableRelationModelLists.size() - 1)
						.setTable2Fileds_text(table2Fileds.getText());

			}
		}

		// 如果集合大小為0,說明沒配
		if (tableRelationModelLists.size() == 0) {

			JOptionPane.showMessageDialog(frame, "請先配置關聯表資訊!!!", "提示", JOptionPane.INFORMATION_MESSAGE);
			return false;

		}

		// 檢查關聯表配置有沒有字段為空
		for (int i = 0; i < tableRelationModelLists.size(); i++) {

			TableRelationModel tableRelationModel = tableRelationModelLists.get(i);

			if ("".equals(tableRelationModel.getTable1_text()) || "".equals(tableRelationModel.getTable1Fileds_text())
					|| "".equals(tableRelationModel.getTable2Fileds_text())) {
				JOptionPane.showMessageDialog(frame, "表1,表1字段,表2字段不能為空!!請填寫!!", "錯誤", JOptionPane.ERROR_MESSAGE);
				return false;

			}

			// 動态表名稱使用
			tableMap.put(tableRelationModel.getTable1_text(), tableRelationModel.getAnotherTableName());

		}
		return true;

	}
}
           

處理一下沒有的依賴,稍微一鼓搗應該就可以直接運作起來。接下來我們來看一下添加的幾個主要的freemarker模闆。

添加的主要模闆

此次更新主要添加了IMutiTableDao.ftl,IMutiTableService.ftl,MutiTableService.ftl,mutiTableHtml.ftl,MutiTableSqlMapper.ftl,mybatis-config.ftl這幾個freemarker模闆,同時對現存的某些模闆做了微小的改動,在這裡我把有關多表查詢的方法全部放在了MutiTableService這個類裡,看一下源碼:

package ${packageName}.service.impl;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ${packageName}.dao.IMutiTableDao;
import ${packageName}.service.IMutiTableService;
import ${packageName}.utils.CastUtil;
import ${packageName}.utils.ExcelUtil;

@Service
public class MutiTableService implements IMutiTableService {

	@Autowired
	private IMutiTableDao dao;

	private Map<String, Object> commonSelect(Map<String, Object> map, String modelName) throws Exception {

		List<String> orderData = CastUtil.cast(map.get("orderData"));

		String orderStr = "";
		for (int i = 0; i < orderData.size(); i++) {
			if (i == orderData.size() - 1) {
				orderStr += orderData.get(i);
				break;
			}
			orderStr += orderData.get(i) + ",";
		}

		Integer currentPage = (Integer) map.get("currentPage");

		Integer start = (currentPage - 1) * 10;

		Long totalPage = 1L;

		// sql中的start
		map.put("start", start);
		// 每頁顯示10條
		map.put("pageSize", 10);

		// 排序條件
		map.put("orderStr", orderStr);

		// 擷取總個數
		Method getCountMethod = dao.getClass().getMethod(modelName + "SelectCount", Map.class);
		Long totalCount = (Long) getCountMethod.invoke(dao, map);

		Method getResultListMethod = dao.getClass().getMethod(modelName + "Select", Map.class);
		List<Map<String, Object>> resultList = CastUtil.cast(getResultListMethod.invoke(dao, map));

		if (totalCount != 0) {

			if (totalCount % 10 == 0) {
				totalPage = totalCount / 10;
			} else {
				totalPage = totalCount / 10 + 1;
			}

		}

		map.clear();
		// 目前頁
		map.put("currentPage", currentPage);

		map.put("count", totalCount);

		map.put("totalPage", totalPage);

		map.put("result", resultList);

		return map;

	}
	
	<#list tablesQueryMap?keys as key>
	<#assign tableFiledModels = tablesQueryMap["${key}"].tableFiledModels/>
	/**
	 * ${key}查詢
	 * 
	 */
	@Override
	public Map<String, Object> ${key}Select(Map<String, Object> map) {
	
		try {
			return commonSelect(map, "${key}");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	/**
	 * ${key}導出excel
	 * 
	 */
	@Override
	public void ${key}ExportExcel(HttpServletResponse response) {

		// 擷取頭部資訊
		String[] headList = new String[] {<#list tableFiledModels as data> "${data.filedText_cn}"<#if data_has_next>,</#if></#list>};

		String[] describeList = new String[] {<#list tableFiledModels as data> "${data.filedCommentStr}"<#if data_has_next>,</#if></#list>};

		try {
			ExcelUtil.mutiTablexportExcel(response, dao, "${key}", headList, describeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	</#list>
}
           

這裡把查詢的方法抽取成了一個commonSelect的公共方法,避免代碼備援。另外發現了mybatis的一個坑,如果mybatis查詢的某個字段為null,預設查出來的結果會不包含這個字段的key,為了避免這種現象的發生,特地加了一個全局配置:mybatis-config.ftl,源碼如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="callSettersOnNulls" value="true"/>
    </settings>
</configuration>
           

最終運作效果

軟體的主界面做了一項更改,原來資料表必須要配置才行,現在可以選擇不配置,其實所有的資訊都可以不配置,直接生成代碼就是最原始的架構,但是寫的代碼有些耦合,以後再修改吧,如圖:

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

資料項配置就不看了,直接去進階配置下的多表聯查配置,配置好資訊,如圖:

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

在這裡我是用一個中間表關聯了兩個主表,看一下資料庫結構:

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

patientrelmedicine(中間表)表的patientNo對應patient(病人)表的caseNO,medicineId對應medicinemsg(藥物資訊)表的id,這三個字段使用left join相關聯,擷取的就是所有病人對應的開藥資訊了。

配置多表查詢的時候有一點需要注意,每次配置完第一個關聯表子產品需要點選一下後面的确定,不然不會生效。也就是這麼個順序:關聯表配置——》點選後面的确定——》查詢字段配制 or 條件字段配置——》點選下方确定。

确定後回到主界面,這裡以springboot為例,生成代碼:

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

點選是即可:

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

看一下生成的項目:

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

讓我們看一下生成的mapper檔案,代碼如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="freeout.dao.IMutiTableDao">

	
		<select id="patientrelmedicineSelect" parameterType="java.util.HashMap"
		resultType="java.util.LinkedHashMap">
		
		
			select
			
				T1.caseNo T1_caseNo,
				T1.name T1_name,
				T1.sex T1_sex,
				T2.name T2_name,
				T2.price T2_price,
				T2.addTime T2_addTime
			
			 from patientrelmedicine T0  left join patient T1 ON T1.caseNo = T0.patientNo left join medicinemsg T2 ON T2.id = T0.medicineId
			<where>
						<if test="T1_name != null and T1_name != '' ">
						and T1.name <![CDATA[=]]> #{T1_name}
						</if>
						<if test="T1_sex != null and T1_sex != '' ">
						and T1.sex <![CDATA[=]]> #{T1_sex}
						</if>
						and T2.status <![CDATA[=]]> '0'
			</where>
			<if test="orderStr != '' and orderStr != null">
				order by ${orderStr}
			</if>
			<if test="start != null and pageSize != null">
				limit #{start},#{pageSize}
			</if>
		
		
	</select>
		
	<select id="patientrelmedicineSelectCount" parameterType="java.util.HashMap"
		resultType="java.lang.Long">

		SELECT
		count(1)
		 from patientrelmedicine T0  left join patient T1 ON T1.caseNo = T0.patientNo left join medicinemsg T2 ON T2.id = T0.medicineId
		<where>
			<if test="T1_name != null and T1_name != '' ">
			and T1.name <![CDATA[=]]> #{T1_name}
			</if>
			<if test="T1_sex != null and T1_sex != '' ">
			and T1.sex <![CDATA[=]]> #{T1_sex}
			</if>
			and T2.status <![CDATA[=]]> '0'
		</where>
	</select>
	
</mapper>
           

這裡生成的sql還是比較規範的,同時也生成了表和字段的别名,主要是為了避免名稱重複,出現錯誤。

把生成的項目跑起來,界面如下:

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

多表查詢的界面已經生成,還是比較不錯的。

測試一下導出excel,生成的excel如下,沒有問題。

ssm,springboot代碼生成器——多表查詢初登場多表查詢UI界面添加的主要模闆最終運作效果

順便提一句,單表查詢子產品的更新和删除功能之前由于模闆更新錯誤,導緻點選不生效的問題已經解決!

本次更新就到此結束了,主要是增加了多表查詢這麼一個大的功能模闆以及一些細節的優化處理,下一步看一下能不能增加圖表支援或者多弄幾套前台模闆,現在的前台模闆就一個,實在是有些單調,加油!

連結:https://pan.baidu.com/s/1L5gP5sH3LFKA8ZPurPmGhQ

提取碼:wxpp

csdn下載下傳連結https://download.csdn.net/download/m0_37719874/11249186

繼續閱讀