MyException - 我的异常网
当前位置:我的异常网» MySQL » weibo4j顶用到的mysql2bean的java工具

weibo4j顶用到的mysql2bean的java工具

www.MyException.Cn  网友分享于:2013-12-15  浏览:1次
weibo4j中用到的mysql2bean的java工具

这是JAVANIU作者根据网友的代码改写的。整理一下,发表上来。

原文下载地址:点击打开链接

由于时间紧迫,对代码质量没有做过多要求,大家有需要的也可以改写下。

主要是这块的逻辑。

String sql = "show tables";
    ResultSet rs = DBManager.query(conn, sql);
    try {
        List<String> tablenames = new ArrayList<String>();
        while (rs.next()) {
            String tablename = rs.getString(1);
            // 生成module
            parseTableByShowCreateModule(conn, tablename, packname,
                    outputdir);
            // 生成repository
            parseTableByShowCreateRepository(conn, tablename, packname,
                    outputdir);
            // 生成service
            parseTableByShowCreateService(conn, tablename, packname,
                    outputdir);
            // 生成serviceimpl
            parseTableByShowCreateServiceImpl(conn, tablename, packname,
                    outputdir);

            // 生成controller
            parseTableByShowCreateController(conn, tablename, packname,
                    outputdir);
            tablenames.add(tablename);
        }

        // 生成basecontroller
        parseTableByShowCreateBaseController(conn, tablenames, packname,
                outputdir);
        DBManager.close(conn, null, rs);
    } catch (SQLException e) {
        e.printStackTrace();
    }

DBManager.java

package com.javaniu;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

//本类专门用来连接数据库,可以作为固定的工具类使用(记下来即可)
public class DBManager {
	// 定义一个静态的连接对象用来连接数据库
	// private static Connection conn = null;
	// 定一个静态的语句对象,用来执行sql语句
	// private static Statement stmt = null;
	// 定义一个静态的结果集对象用来存放执行sql语句后查询得到的结果
	// private static ResultSet rs = null;

	/**
	 * 连接数据库的方法
	 * 
	 * @return conn 返回一个连接对象
	 */
	public static Connection mssql(String url, String user, String pass) {
		Connection conn = null;
		try {
			// 1、加载连接驱动
			// "jdbc:odbc:bookdemo"
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			// 2、连接到数据库(获得连接对象)
			// 通过连接管理器(DriverManager)类的一个方法来获得连接对象,里面的参数表示我们连接到数据源bookdemo
			conn = DriverManager.getConnection(url, user, pass);
		} catch (ClassNotFoundException e) {
			// 以堆栈的方式将错误信息打印出来
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return conn; // 将连接对象返回
	}

	/**
	 * 连接数据库的方法
	 * 
	 * @return conn 返回一个连接对象
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection mysql(String url, String user, String pass)
			throws ClassNotFoundException, SQLException {
		Connection conn = null;

		// 1、加载连接驱动
		// "jdbc:odbc:bookdemo"
		Class.forName("com.mysql.jdbc.Driver");
		// 2、连接到数据库(获得连接对象)
		// 通过连接管理器(DriverManager)类的一个方法来获得连接对象,里面的参数表示我们连接到数据源bookdemo
		conn = DriverManager.getConnection(url, user, pass);

		return conn; // 将连接对象返回
	}

	/**
	 * 动漫网的mysql数据库连接
	 * 
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public static Connection mysql(String host, String database, String user,
			String pass) throws ClassNotFoundException, SQLException {
		String url = "jdbc:mysql://" + host + "/" + database
				+ "?useUnicode=true&characterEncoding=utf-8";
		return mysql(url, user, pass);
	}

	/**
	 * 本函数用来执行用户传入的sql语句(仅限于select语句)
	 * 
	 * @param sql
	 *            传入的sql语句,等待执行
	 * @return 返回执行sql语句后的结果集对象
	 */
	public static ResultSet query(Connection conn, String sql) {
		ResultSet rs = null;
		try {
			// 3、通过连接对象创建一个语句对象stmt,用来执行sql语句
			Statement stmt = conn.createStatement();
			// 4、执行sql语句,得到一个rs(结果集对象)
			rs = stmt.executeQuery(sql);
		} catch (Exception e) { // 错误处理,暂时不用理会
			e.printStackTrace();
		}
		return rs; // 将查询得到的结果集对象返回
	}

	/**
	 * 本方法用来执行更新语句,并返回影响了多少行(insert,update,delete)
	 * 
	 * @param sql
	 *            传入的sql语句,等待执行
	 * @return 返回执行sql语句后的结果集对象
	 */
	public static int update(Connection conn, String sql) {
		// 执行sql语句前先连接到数据库
		Statement stmt = null;
		int i = 0;
		try {
			// 通过连接对象创建一个语句对象stmt,用来执行sql语句
			stmt = conn.createStatement();
			// 执行更新语句,并返回影响了多少行
			i = stmt.executeUpdate(sql);
		} catch (Exception e) { // 错误处理,暂时不用理会
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return i;
	}

	public static void close(Connection conn, Statement stmt, ResultSet rs) {

		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

MySQLToBean.java
package com.javaniu;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MySQLToBean extends JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JCheckBox checkBox;
	Properties p = new Properties();
	String configFile = "config.ini";
	private JLabel lblNewLabel_4;

	public MySQLToBean() {

		setResizable(false);

		setTitle("MySQL生成javabean小工具");
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

		setBounds(100, 100, 484, 324);

		JPanel panel = new JPanel();
		getContentPane().add(panel, BorderLayout.CENTER);
		panel.setLayout(null);

		txtLocalhost = new JTextField();
		txtLocalhost.setText("localhost");
		txtLocalhost.setBounds(146, 10, 147, 21);
		panel.add(txtLocalhost);
		txtLocalhost.setColumns(10);

		JLabel lblIp = new JLabel("IP:");
		lblIp.setBounds(80, 13, 30, 15);
		panel.add(lblIp);

		JLabel label = new JLabel("数据库:");
		label.setBounds(80, 42, 54, 15);
		panel.add(label);

		textField = new JTextField();
		textField.setBounds(146, 39, 147, 21);
		textField.setText("weibo4j");
		panel.add(textField);
		textField.setColumns(10);

		JLabel label_1 = new JLabel("表名:");
		label_1.setBounds(80, 127, 54, 15);
		panel.add(label_1);

		textField_1 = new JTextField();
		textField_1.setBounds(146, 124, 147, 21);
		panel.add(textField_1);
		textField_1.setColumns(10);

		JLabel label_2 = new JLabel("包名:");
		label_2.setBounds(79, 156, 54, 15);
		panel.add(label_2);

		txtComyourcom = new JTextField();
		txtComyourcom.setText("com.javaniu.weibo4j");
		txtComyourcom.setBounds(146, 155, 147, 21);
		panel.add(txtComyourcom);
		txtComyourcom.setColumns(10);

		JLabel lblNewLabel = new JLabel("输出目录:");
		lblNewLabel.setBounds(80, 190, 65, 15);
		panel.add(lblNewLabel);

		textField_3 = new JTextField();
		textField_3.setBounds(146, 186, 147, 21);
		textField_3.setText("c:/");
		panel.add(textField_3);
		textField_3.setColumns(10);

		checkBox = new JCheckBox("生成包结构目录");
		checkBox.setSelected(true);
		checkBox.setBounds(145, 213, 147, 23);
		panel.add(checkBox);

		JLabel lblNewLabel_1 = new JLabel("可以指定表名,也可以不指定");
		lblNewLabel_1.setBounds(303, 127, 176, 15);
		panel.add(lblNewLabel_1);

		JLabel lblNewLabel_2 = new JLabel("* 数据库名");
		lblNewLabel_2.setForeground(Color.RED);
		lblNewLabel_2.setBounds(303, 42, 66, 15);
		panel.add(lblNewLabel_2);

		JLabel lblNewLabel_3 = new JLabel("* 包结构");
		lblNewLabel_3.setForeground(Color.RED);
		lblNewLabel_3.setBounds(303, 158, 79, 15);
		panel.add(lblNewLabel_3);

		JButton button = new JButton("执行");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				go();
			}
		});
		button.setBounds(145, 242, 93, 23);
		panel.add(button);

		textField_4 = new JTextField();
		textField_4.setText("111111");
		textField_4.setBounds(145, 93, 147, 21);
		panel.add(textField_4);
		textField_4.setColumns(10);

		txtRoot = new JTextField();
		txtRoot.setText("root");
		txtRoot.setBounds(145, 66, 148, 21);
		panel.add(txtRoot);
		txtRoot.setColumns(10);

		JLabel label_3 = new JLabel("用户名:");
		label_3.setBounds(80, 69, 54, 15);
		panel.add(label_3);

		JLabel label_4 = new JLabel("密码:");
		label_4.setBounds(80, 96, 54, 15);
		panel.add(label_4);

		lblNewLabel_4 = new JLabel("");
		lblNewLabel_4.setForeground(Color.RED);
		lblNewLabel_4.setBounds(248, 242, 204, 23);
		panel.add(lblNewLabel_4);

		addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				super.windowClosing(e);
				// export();
				System.exit(0);
			}

		});

		// inport();
	}

	static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private JTextField txtLocalhost;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField txtComyourcom;
	private JTextField textField_3;
	private JTextField textField_4;
	private JTextField txtRoot;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//
		// String field = "create_time";
		// int idx = field.indexOf("_");
		// if (idx != -1) {
		// String temp = field.substring(idx + 1, idx + 2);
		// String temp2 = new MySQLToBean().upperFirestChar(temp);
		// field = field.replaceFirst("_" + temp, temp2);
		// }
		// System.out.println(field);

		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {

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

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

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

			e.printStackTrace();
		}
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MySQLToBean frame = new MySQLToBean();
					frame.setLocationRelativeTo(null);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void inport() {
		File config = new File(configFile);
		if (config.exists()) {
			try {
				InputStream is = new FileInputStream(config);
				p.load(is);
				is.close();
				setUIVal();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			try {
				config.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public void setUIVal() {
		txtLocalhost.setText(p.getProperty("host", "localhost"));
		textField.setText(p.getProperty("database", "javaniu2"));
		txtRoot.setText(p.getProperty("user", "root"));
		textField_4.setText(p.getProperty("pass", "111111"));
		txtComyourcom.setText(p.getProperty("packname", "com.javaniu.weibo4j"));
		textField_3.setText(p.getProperty("dirstr", "c:/"));
		textField_1.setText(p.getProperty("tablename", ""));
	}

	private void export() {
		String host = txtLocalhost.getText();
		String database = textField.getText();
		String user = txtRoot.getText();
		String pass = textField_4.getText();
		String packname = txtComyourcom.getText();
		String dirstr = textField_3.getText();// 空表示当前目录
		String tablename = textField_1.getText();

		p.setProperty("host", host);
		p.setProperty("database", database);
		p.setProperty("user", user);
		p.setProperty("pass", pass);
		p.setProperty("packname", packname);
		p.setProperty("dirstr", dirstr);
		p.setProperty("tablename", tablename);

		try {
			OutputStream out = new FileOutputStream(configFile);
			p.store(out, "退出保存文件," + sdf.format(new Date()));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void setTips(String msg) {
		lblNewLabel_4.setText(msg);
	}

	public void go() {
		String host = txtLocalhost.getText();
		String database = textField.getText();

		if (database.length() == 0) {
			setTips("数据库名必填");
			return;
		}

		String user = txtRoot.getText();
		String pass = textField_4.getText();
		String packname = txtComyourcom.getText();
		String dirstr = textField_3.getText();// 空表示当前目录
		String tablename = textField_1.getText();
		boolean createPackage = checkBox.getSelectedObjects() != null;
		System.out.println(createPackage);
		if (dirstr != null && !dirstr.isEmpty()) {
			if (!dirstr.endsWith("/")) {
				dirstr += "/";
			}
		}
		File dir = new File(dirstr);
		if (createPackage) {
			dir = new File(dirstr + packname.replaceAll("\\.", "/"));
			if (!dir.exists()) {
				dir.mkdirs();
			}
		}
		String outputdir = dir.getAbsolutePath();// bean的生成目录

		Connection conn = null;
		try {

			conn = DBManager.mysql(host, database, user, pass);
			if (tablename.length() > 0) {
				parseTableByShowCreateModule(conn, tablename, packname,
						outputdir);
			} else {
				parseAllTable(conn, packname, outputdir);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			setTips("找不到MySQL的jar包");
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 开始处理生成所有表 如果不传入表名,表示将数据库中所有表生成bean; 可以指定表名生成bean;
	 */
	public void parseAllTable(Connection conn, String packname, String outputdir) {

		String sql = "show tables";
		ResultSet rs = DBManager.query(conn, sql);
		try {
			List tablenames = new ArrayList();
			while (rs.next()) {
				String tablename = rs.getString(1);
				// 生成module
				parseTableByShowCreateModule(conn, tablename, packname,
						outputdir);
				// 生成repository
				parseTableByShowCreateRepository(conn, tablename, packname,
						outputdir);
				// 生成service
				parseTableByShowCreateService(conn, tablename, packname,
						outputdir);
				// 生成serviceimpl
				parseTableByShowCreateServiceImpl(conn, tablename, packname,
						outputdir);

				// 生成controller
				parseTableByShowCreateController(conn, tablename, packname,
						outputdir);
				tablenames.add(tablename);
			}

			// 生成basecontroller
			parseTableByShowCreateBaseController(conn, tablenames, packname,
					outputdir);
			DBManager.close(conn, null, rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 通过 mysql的 show create table TABLE_NAME逆向生成Bean;
	 * 
	 * @param conn
	 * @param tname
	 * @param outputdir
	 * @param packname
	 */
	private void parseTableByShowCreateModule(Connection conn,
			String tablename, String packname, String outputdir) {
		StringBuilder classInfo = new StringBuilder("/**\r\n\t*");
		String sql = "show create table " + tablename;
		String _tablename = tablename;
		tablename = replaceS(tablename);
		ResultSet rs = null;
		try {
			rs = DBManager.query(conn, sql);
			StringBuilder fields = new StringBuilder();
			StringBuilder methods = new StringBuilder();

			while (rs.next()) {
				String sqlstr = rs.getString(2);
				String lines[] = sqlstr.split("\r\n");
				for (int i = 0; i < lines.length; i++) {
					String line = lines[i];
					System.out.println(line);
					// System.out.println("------------");
					String regex = "\\s*`([^`]*)`\\s*(\\w+[^ ]*)\\s*(NOT\\s+NULL\\s*)?(AUTO_INCREMENT\\s*)?(DEFAULT\\s*([^ ]*|NULL|'0'|''|CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)\\s*)?(COMMENT\\s*'([^']*)')?\\s*,\\s*";
					Pattern p = Pattern.compile(regex);
					Matcher m = p.matcher(line);
					while (m.find()) {
						String field = m.group(1);
						if (field.equals("created_at")) {
							continue;
						}
						if (field.equals("id")) {
							continue;
						}
						field = replaceS(field);
						String type = typeTrans(m.group(2));
						fields.append(getFieldStr(field, type));
						methods.append(getMethodStr(field, type));
					}
					if (i == lines.length - 1) {
						classInfo.append("*@author javaniu\r\n");
						classInfo.append(sdf.format(new Date()));
						classInfo.append("\r\n*/\r\n");
					}

				}
			}

			classInfo.append("import javax.persistence.Entity;\n");
			classInfo.append("import javax.persistence.Table;\n");
			classInfo.append("import org.apache.commons.lang.builder.ToStringBuilder;\n");
			classInfo.append("import java.util.Date;\n");
			
			classInfo.append("@Entity\n");
			classInfo.append("@Table(name = \"" + _tablename + "\")\n");
			classInfo.append("public class ")
					.append(tablename + " extends BaseEntity").append("{\r\n");
			classInfo.append(fields);
			classInfo.append("\t public " + tablename + "() {\n");
			classInfo.append("\t \tthis.createAt = new Date();\n");
			classInfo.append("\t }\n");
			classInfo.append(methods);
			classInfo.append("\t @Override\n");
			classInfo.append("\t public String toString() {\n");
			classInfo
					.append("\t \treturn ToStringBuilder.reflectionToString(this);\n");
			classInfo.append("\t }");
			classInfo.append("\r\n");
			classInfo.append("}");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		String packageinfo = "package " + packname + ".module;\r\n\r\n";
		File file = new File(outputdir + "/module", tablename + ".java");
		System.out.println(file.getAbsolutePath());
		try {
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			FileWriter fw = new FileWriter(file);
			fw.write(packageinfo);
			fw.write(classInfo.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void parseTableByShowCreateRepository(Connection conn,
			String tablename, String packname, String outputdir) {
		StringBuilder classInfo = new StringBuilder("");
		tablename = replaceS(tablename);

		classInfo
				.append("import org.springframework.data.jpa.repository.JpaRepository;\n");
		classInfo.append("import com.javaniu.weibo4j.module." + tablename
				+ ";\n");

		classInfo.append("\t/**\r\n\t*");
		classInfo.append("\t*@author javaniu\r\n");
		classInfo.append(sdf.format(new Date()));
		classInfo.append("\r\n\t*/\r\n\r\n");

		classInfo.append("public interface ").append(tablename + "Repository")
				.append(" extends JpaRepository<" + tablename + ", Long>")
				.append("{\r\n");
		classInfo.append("\r\n");
		classInfo.append("}");

		String packageinfo = "package " + packname + ".repository;\r\n\r\n";
		File file = new File(outputdir + "/repository", tablename
				+ "Repository.java");
		System.out.println(file.getAbsolutePath());
		try {
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			FileWriter fw = new FileWriter(file);
			fw.write(packageinfo);
			fw.write(classInfo.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void parseTableByShowCreateService(Connection conn,
			String tablename, String packname, String outputdir) {
		StringBuilder classInfo = new StringBuilder("");
		tablename = replaceS(tablename);
		classInfo.append("import com.javaniu.weibo4j.module." + tablename
				+ ";\n");
		classInfo.append("import java.util.List;\n");

		classInfo.append("\t/**\r\n\t*");
		classInfo.append("\t*@author javaniu\r\n");
		classInfo.append(sdf.format(new Date()));
		classInfo.append("\r\n\t*/\r\n\r\n");
		classInfo.append("public interface ").append(tablename + "Service")
				.append("{\r\n");
		classInfo.append("\t public void save(" + tablename + " "
				+ lowerFirestChar(tablename) + ");\n");
		classInfo.append("\t public void save(List<" + tablename + "> "
				+ lowerFirestChar(tablename) + "s);\n");
		classInfo.append("\t public void delete(long id);\n");
		classInfo.append("\t public " + tablename + " findById(long id);\n");
		classInfo.append("\t public Iterable<" + tablename
				+ "> findByIds(List ids);\n");
		classInfo.append("}");

		String packageinfo = "package " + packname + ".service;\r\n\r\n";
		File file = new File(outputdir + "/service", tablename + "Service.java");
		System.out.println(file.getAbsolutePath());
		try {
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			FileWriter fw = new FileWriter(file);
			fw.write(packageinfo);
			fw.write(classInfo.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void parseTableByShowCreateServiceImpl(Connection conn,
			String tablename, String packname, String outputdir) {
		StringBuilder classInfo = new StringBuilder("");
		tablename = replaceS(tablename);

		classInfo.append("import org.springframework.stereotype.Service;\n");
		classInfo.append("import com.javaniu.weibo4j.service." + tablename
				+ "Service;\n");
		classInfo.append("import com.javaniu.weibo4j.module." + tablename
				+ ";\n");

		classInfo.append("import java.util.List;\n");
		classInfo.append("import com.javaniu.weibo4j.repository." + tablename
				+ "Repository;\n");
		classInfo
				.append("import org.springframework.transaction.annotation.Transactional;\n");
		classInfo.append("import javax.annotation.Resource;\n");

		classInfo.append("\t/**\r\n\t*");
		classInfo.append("\t*@author javaniu\r\n");
		classInfo.append(sdf.format(new Date()));
		classInfo.append("\r\n\t*/\r\n\r\n");
		classInfo.append("@Service\n");
		classInfo.append("@Transactional(readOnly = true)\n");
		classInfo
				.append("public class ")
				.append(tablename + "ServiceImpl implements " + tablename
						+ "Service").append("{\r\n");
		classInfo.append("@Resource\n");
		classInfo.append("private " + tablename + "Repository "
				+ lowerFirestChar(tablename) + "Repository;\n");

		classInfo.append("\t @Override\n");
		classInfo.append("\t @Transactional(readOnly = false)\n");
		classInfo.append("\t public void save(" + tablename + " "
				+ lowerFirestChar(tablename) + ") {\n");
		classInfo.append("\t \t " + lowerFirestChar(tablename)
				+ "Repository.save(" + lowerFirestChar(tablename) + ");\n");
		classInfo.append("\t }\n");

		classInfo.append("\t @Override\n");
		classInfo.append("\t @Transactional(readOnly = false)\n");
		classInfo.append("\t public void save(List<" + tablename + "> "
				+ lowerFirestChar(tablename) + "s) {\n");
		classInfo.append("\t \t " + lowerFirestChar(tablename)
				+ "Repository.save(" + lowerFirestChar(tablename) + "s);\n");
		classInfo.append("}\n");

		classInfo.append("\t @Override\n");
		classInfo.append("\t @Transactional(readOnly = false)\n");
		classInfo.append("\t public void delete(long id) {\n");
		classInfo.append("\t \t " + lowerFirestChar(tablename)
				+ "Repository.delete(id);\n");
		classInfo.append("\t }\n");

		classInfo.append("\t @Override\n");
		classInfo.append("\t public " + tablename + " findById(long id) {\n");
		classInfo.append("\t \t return " + lowerFirestChar(tablename)
				+ "Repository.findOne(id);\n");
		classInfo.append("\t }\n");

		classInfo.append("\t @Override\n");
		classInfo.append("\t public Iterable<" + tablename
				+ "> findByIds(List ids) {\n");
		classInfo.append("\t \t return " + lowerFirestChar(tablename)
				+ "Repository.findAll(ids);\n");
		classInfo.append("\t }\n");

		classInfo.append("}");

		String packageinfo = "package " + packname + ".service.impl;\r\n\r\n";
		File file = new File(outputdir + "/service/impl/", tablename
				+ "ServiceImpl.java");
		System.out.println(file.getAbsolutePath());
		try {
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			FileWriter fw = new FileWriter(file);
			fw.write(packageinfo);
			fw.write(classInfo.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void parseTableByShowCreateBaseController(Connection conn,
			List tablenames, String packname, String outputdir) {
		String packageinfo = "package " + packname + ".controller;\r\n\r\n";

		StringBuilder classInfo = new StringBuilder("");
		classInfo
				.append("import org.springframework.beans.factory.annotation.Autowired;\n");
		for (String tablename : tablenames) {
			tablename = replaceS(tablename);
			classInfo.append("import com.javaniu.weibo4j.service." + tablename
					+ "Service;\n");
		}
		classInfo.append("public abstract class BaseController")
				.append("{\r\n");
		for (String tablename : tablenames) {
			tablename = replaceS(tablename);
			classInfo.append("\t @Autowired\n");
			classInfo.append("\t public " + tablename + "Service "
					+ lowerFirestChar(tablename) + "Service;\n");
		}
		classInfo.append("}");

		File file = new File(outputdir + "/controller", "BaseController.java");
		System.out.println(file.getAbsolutePath());
		try {
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			FileWriter fw = new FileWriter(file);
			fw.write(packageinfo);
			fw.write(classInfo.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void parseTableByShowCreateController(Connection conn,
			String tablename, String packname, String outputdir) {
		StringBuilder classInfo = new StringBuilder("");
		String _tablename = tablename;
		tablename = replaceS(tablename);

		classInfo.append("import org.springframework.stereotype.Controller;\n");
		classInfo
				.append("import org.springframework.web.bind.annotation.RequestMapping;\n");

		classInfo.append("\t/**\r\n\t*");
		classInfo.append("\t*@author javaniu\r\n");
		classInfo.append(sdf.format(new Date()));
		classInfo.append("\r\n\t*/\r\n\r\n");
		classInfo.append("@Controller\n");
		classInfo.append("@RequestMapping({ \"/" + _tablename + "\" })\n");
		classInfo.append("public class ")
				.append(tablename + "Controller extends BaseController")
				.append("{\r\n");

		classInfo.append("}");

		String packageinfo = "package " + packname + ".controller;\r\n\r\n";
		File file = new File(outputdir + "/controller/", tablename
				+ "Controller.java");
		System.out.println(file.getAbsolutePath());
		try {
			File parent = file.getParentFile();
			if (!parent.exists()) {
				parent.mkdirs();
			}
			FileWriter fw = new FileWriter(file);
			fw.write(packageinfo);
			fw.write(classInfo.toString());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param type
	 * @return
	 */
	private String getMethodStr(String field, String type) {
		StringBuilder get = new StringBuilder("\tpublic ");
		get.append(type).append(" ");
		if (type.equals("boolean")) {
			get.append(field);
		} else {
			get.append("get");
			get.append(field);
		}
		get.append("(){").append("\r\n\t\treturn this.")
				.append(lowerFirestChar(field)).append(";\r\n\t}\r\n");
		StringBuilder set = new StringBuilder("\tpublic void ");

		if (type.equals("boolean")) {
			set.append(field);
		} else {
			set.append("set");
			set.append(field);
		}
		set.append("(").append(type).append(" ").append(lowerFirestChar(field))
				.append("){\r\n\t\tthis.").append(lowerFirestChar(field))
				.append("=").append(lowerFirestChar(field))
				.append(";\r\n\t}\r\n");
		get.append(set);
		return get.toString();
	}

	public String upperFirestChar(String src) {
		return src.substring(0, 1).toUpperCase().concat(src.substring(1));
	}

	public String lowerFirestChar(String src) {
		return src.substring(0, 1).toLowerCase().concat(src.substring(1));
	}

	private String getFieldStr(String field, String type) {
		StringBuilder sb = new StringBuilder();
		sb.append("\t").append("private ").append(type).append(" ")
				.append(lowerFirestChar(field)).append(";");
		sb.append("\r\n");
		return sb.toString();
	}

	/**
	 * mysql的类型转换到java 类型参考文章
	 * http://hi.baidu.com/wwtvanessa/blog/item/9fe555945a07bd16d31b70cd.html
	 */
	public String typeTrans(String type) {
		if (type.contains("tinyint")) {
			return "boolean";
		} else if (type.contains("bigint")) {
			return "long";
		} else if (type.contains("int")) {
			return "int";
		} else if (type.contains("varchar") || type.contains("date")
				|| type.contains("time") || type.contains("datetime")
				|| type.contains("timestamp") || type.contains("text")
				|| type.contains("enum") || type.contains("set")) {
			return "String";
		} else if (type.contains("binary") || type.contains("blob")) {
			return "byte[]";
		} else {
			return "String";
		}
	}

	public String replaceS(String input) {
		StringBuffer output = new StringBuffer();

		int idx = input.indexOf("_");
		if (idx == -1) {
			output.append(new MySQLToBean().upperFirestChar(input));
		} else {
			String[] inputs = input.split("_");
			for (String _input : inputs) {
				output.append(new MySQLToBean().upperFirestChar(_input));
			}
		}
		return output.toString();
	}
}

文章评论

我的丈夫是个程序员
我的丈夫是个程序员
鲜为人知的编程真相
鲜为人知的编程真相
10个帮程序员减压放松的网站
10个帮程序员减压放松的网站
Java 与 .NET 的平台发展之争
Java 与 .NET 的平台发展之争
我跳槽是因为他们的显示器更大
我跳槽是因为他们的显示器更大
当下全球最炙手可热的八位少年创业者
当下全球最炙手可热的八位少年创业者
为啥Android手机总会越用越慢?
为啥Android手机总会越用越慢?
科技史上最臭名昭著的13大罪犯
科技史上最臭名昭著的13大罪犯
程序员的一天:一寸光阴一寸金
程序员的一天:一寸光阴一寸金
写给自己也写给你 自己到底该何去何从
写给自己也写给你 自己到底该何去何从
程序员最害怕的5件事 你中招了吗?
程序员最害怕的5件事 你中招了吗?
“肮脏的”IT工作排行榜
“肮脏的”IT工作排行榜
总结2014中国互联网十大段子
总结2014中国互联网十大段子
程序员必看的十大电影
程序员必看的十大电影
聊聊HTTPS和SSL/TLS协议
聊聊HTTPS和SSL/TLS协议
不懂技术不要对懂技术的人说这很容易实现
不懂技术不要对懂技术的人说这很容易实现
5款最佳正则表达式编辑调试器
5款最佳正则表达式编辑调试器
什么才是优秀的用户界面设计
什么才是优秀的用户界面设计
初级 vs 高级开发者 哪个性价比更高?
初级 vs 高级开发者 哪个性价比更高?
一个程序员的时间管理
一个程序员的时间管理
Web开发人员为什么越来越懒了?
Web开发人员为什么越来越懒了?
中美印日四国程序员比较
中美印日四国程序员比较
 程序员的样子
程序员的样子
为什么程序员都是夜猫子
为什么程序员都是夜猫子
“懒”出效率是程序员的美德
“懒”出效率是程序员的美德
60个开发者不容错过的免费资源库
60个开发者不容错过的免费资源库
程序员眼里IE浏览器是什么样的
程序员眼里IE浏览器是什么样的
要嫁就嫁程序猿—钱多话少死的早
要嫁就嫁程序猿—钱多话少死的早
亲爱的项目经理,我恨你
亲爱的项目经理,我恨你
程序员周末都喜欢做什么?
程序员周末都喜欢做什么?
每天工作4小时的程序员
每天工作4小时的程序员
程序员应该关注的一些事儿
程序员应该关注的一些事儿
看13位CEO、创始人和高管如何提高工作效率
看13位CEO、创始人和高管如何提高工作效率
程序猿的崛起——Growth Hacker
程序猿的崛起——Growth Hacker
漫画:程序员的工作
漫画:程序员的工作
十大编程算法助程序员走上高手之路
十大编程算法助程序员走上高手之路
Web开发者需具备的8个好习惯
Web开发者需具备的8个好习惯
程序员的鄙视链
程序员的鄙视链
10个调试和排错的小建议
10个调试和排错的小建议
如何成为一名黑客
如何成为一名黑客
代码女神横空出世
代码女神横空出世
程序员和编码员之间的区别
程序员和编码员之间的区别
程序员都该阅读的书
程序员都该阅读的书
老程序员的下场
老程序员的下场
编程语言是女人
编程语言是女人
软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有