JAVA 반 사 를 이용 하여 데이터베이스 테이블 이름 을 읽 고 대응 하 는 실체 클래스 를 자동 으로 생 성 합 니 다.

이 코드 는 자바 반 사 를 이용 하여 데이터베이스 테이블 을 읽 고 자동 으로 테이블 이름 에 따라 실체 클래스 를 생 성 합 니 다.데이터 베 이 스 는 오래된 SQLSERVER 2000 을 사용 하여 JTDS 로 구동 되 며 기타 데이터 베 이 스 는 상황 에 따라 수정 할 수 있 습 니 다.
코드 에는 대부분의 데이터베이스 형식 과 JAVA 형식의 변환 이 포함 되 어 있 으 며,포함 되 지 않 은 소수의 경우 코드 생 성 시 인쇄 되 며,방면 후기 에 수정 사항 을 찾 습 니 다.

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 *            ,       
 * 
 * @author Zero
 *
 */
public class SqlHelper {
	//      
	private String packageOutPath = "com.xxx.entity.system";//             
	private String authorName = "Zero";//     
	private String tablename = "xxx";//   
	private String[] colnames; //     
	private String[] colTypes; //       
	private String version = "V0.01"; //   
	private int[] colSizes; //       
	private boolean f_util = false; //        java.util.*
	private boolean f_sql = false; //        java.sql.*
	private boolean f_lang = false; //        java.sql.*
	private String defaultPath = "/src/main/java/";
	//      
	private static final String URL = "jdbc:jtds:sqlserver://192.168.29.128:1433/xxx";
	private static final String NAME = "sa";
	private static final String PASS = "xxx";
	private static final String DRIVER = "net.sourceforge.jtds.jdbc.Driver";
 
	/*
	 *     
	 */
	public SqlHelper() {
		//     
		Connection con;
		//          
		String sql = "select * from " + tablename;
		PreparedStatement pStemt = null;
		try {
			try {
				Class.forName(DRIVER);
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			con = DriverManager.getConnection(URL, NAME, PASS);
			pStemt = con.prepareStatement(sql);
			ResultSetMetaData rsmd = pStemt.getMetaData();
			int size = rsmd.getColumnCount(); //    
			colnames = new String[size];
			colTypes = new String[size];
			colSizes = new int[size];
			for (int i = 0; i < size; i++) {
 
				colnames[i] = rsmd.getColumnName(i + 1);
				colTypes[i] = rsmd.getColumnTypeName(i + 1);
				//       
				
				
				// if (colTypes[i].equalsIgnoreCase("datetime")) {
				// f_util = true;
				// }
				if (colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")
						|| colTypes[i].equalsIgnoreCase("datetime") || colTypes[i].equalsIgnoreCase("time")
						|| colTypes[i].equalsIgnoreCase("date") || colTypes[i].equalsIgnoreCase("datetime2")) {
					f_sql = true;
				}
				// if (colTypes[i].equalsIgnoreCase("int")) {
				// f_lang = true;
				// }
				colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
			}
 
			String content = parse(colnames, colTypes, colSizes);
 
			try {
				File directory = new File("");
				
				String path = this.getClass().getResource("").getPath();
 
				System.out.println(path);
				
				String outputPath = directory.getAbsolutePath() + this.defaultPath
						+ this.packageOutPath.replace(".", "/") + "/" + initcap(tablename) + ".java";
				System.out.println("    ,     :"+outputPath);
				FileWriter fw = new FileWriter(outputPath);
				PrintWriter pw = new PrintWriter(fw);
				pw.println(content);
				pw.flush();
				pw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
 
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			
		}
	}
 
	/**
	 *   :         
	 * 
	 * @param colnames
	 * @param colTypes
	 * @param colSizes
	 * @return
	 */
	private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
		StringBuffer sb = new StringBuffer();
		//   package   
		sb.append("package " + this.packageOutPath + ";\r
"); // if (f_util) { sb.append("import java.util.Date;\r
"); } if (f_sql) { sb.append("import java.sql.*;\r
"); } if (f_lang) { sb.append("import java.lang.*;\r
"); } sb.append("\r
"); // sb.append(" /**\r
"); sb.append(" * @ :" + this.tablename + ".java\r
"); sb.append(" * @ :" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\r
"); sb.append(" * @ :" + this.authorName + " \r
"); sb.append(" * @ :" + tablename + " \r
"); sb.append(" * @ :" + this.version + " \r
"); sb.append(" */ \r
"); // sb.append("\r
\r
public class " + initcap(tablename) + "{\r
"); processAllAttrs(sb);// processAllMethod(sb);// get set sb.append("}\r
"); // System.out.println(sb.toString()); return sb.toString(); } /** * : * * @param sb */ private void processAllAttrs(StringBuffer sb) { for (int i = 0; i < colnames.length; i++) { sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + ";\r
"); } } /** * : * * @param sb */ private void processAllMethod(StringBuffer sb) { for (int i = 0; i < colnames.length; i++) { sb.append("\tpublic void set" + initcap(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + "){\r
"); sb.append("\tthis." + colnames[i] + "=" + colnames[i] + ";\r
"); sb.append("\t}\r
"); sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(colnames[i]) + "(){\r
"); sb.append("\t\treturn " + colnames[i] + ";\r
"); sb.append("\t}\r
"); } } /** * : * * @param str * @return */ private String initcap(String str) { char[] ch = str.toCharArray(); if (ch[0] >= 'a' && ch[0] <= 'z') { ch[0] = (char) (ch[0] - 32); } return new String(ch); } /** * : * * @param sqlType * @return */ private String sqlType2JavaType(String sqlType) { if (sqlType.equalsIgnoreCase("bit")) { return "Boolean"; } else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("money") || sqlType.equalsIgnoreCase("smallmoney") || sqlType.equalsIgnoreCase("numeric") || sqlType.equalsIgnoreCase("bigint")) { return "Long"; } else if (sqlType.equalsIgnoreCase("float")) { return "Double"; } else if (sqlType.equalsIgnoreCase("int") || sqlType.equalsIgnoreCase("int identity")) { return "Integer"; } else if (sqlType.equalsIgnoreCase("image") || sqlType.equalsIgnoreCase("varbinary(max)") || sqlType.equalsIgnoreCase("varbinary") || sqlType.equalsIgnoreCase("udt") || sqlType.equalsIgnoreCase("timestamp") || sqlType.equalsIgnoreCase("binary")) { return "Byte[]"; } else if (sqlType.equalsIgnoreCase("nchar") || sqlType.equalsIgnoreCase("nvarchar(max)") || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nvarchar(ntext)") || sqlType.equalsIgnoreCase("uniqueidentifier") || sqlType.equalsIgnoreCase("xml") || sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("varchar(max)") || sqlType.equalsIgnoreCase("text") || sqlType.equalsIgnoreCase("varchar")) { return "String"; } else if (sqlType.equalsIgnoreCase("real")) { return "Float"; } else if (sqlType.equalsIgnoreCase("smallint") || sqlType.equalsIgnoreCase("tinyint")) { return "Short"; } else if (sqlType.equalsIgnoreCase("date") || sqlType.equalsIgnoreCase("datetime") || sqlType.equalsIgnoreCase("time") || sqlType.equalsIgnoreCase("datetime2")) { return "Date"; } else { System.out.println(" , :" + sqlType); } return null; } /** * TODO * * @param args */ public static void main(String[] args) { new SqlHelper(); } }
추가 지식:자바 반사 로 클래스 이름,속성 이름 및@Table 주석 에 있 는 표 이름 얻 기
긴 말 안 할 게 요.그냥 코드 보 세 요~

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
/**
 * @author caizw
 * @createDate 2018/2/8
 * @description      
 */
public class ReflectUtils {
 
  /**
   *        
   *
   * @param clazz
   * @return
   */
  public static Field getIdField(Class<?> clazz) {
    Field[] fields = clazz.getDeclaredFields();
    Field item = null;
    for (Field field : fields) {
      Id id = field.getAnnotation(Id.class);
      if (id != null) {
        field.setAccessible(true);
        item = field;
        break;
      }
    }
    if (item == null) {
      Class<?> superclass = clazz.getSuperclass();
      if (superclass != null) {
        item = getIdField(superclass);
      }
    }
    return item;
  }
 
  /**
   *                 
   *
   * @param clazz
   * @param pkName
   * @return
   */
  public static Object getPkValueByName(Object clazz, String pkName) {
    try {
      String firstLetter = pkName.substring(0, 1).toUpperCase();
      String getter = "get" + firstLetter + pkName.substring(1);
      Method method = clazz.getClass().getMethod(getter, new Class[]{});
      Object value = method.invoke(clazz, new Object[]{});
      return value;
    } catch (Exception e) {
      return null;
    }
  }
 
  /**
   *       class1        class2
   *
   * @param class1
   * @param class2
   * @throws Exception
   */
  public static void reflectClass1ToClass2(Object class1, Object class2) throws Exception {
    Field[] field = class1.getClass().getDeclaredFields();
    for (int i = 0; i < field.length; i++) {
      String name = field[i].getName();
      if ("serialVersionUID".equals(name)) {
        continue;
      }
      name = name.substring(0, 1).toUpperCase() + name.substring(1);
      Method m1 = class1.getClass().getMethod("get" + name);
      Object value = m1.invoke(class1);
      if (value != null) {
        Field f = field[i];
        f.setAccessible(true);
        f.set(class2, value);
      }
    }
  }
 
  /**
   *       @Column          
   *
   * @param clazz
   * @return
   */
  public static Map<String, String> getColumnName(Class<?> clazz) {
    Map<String, String> map = new ConcurrentHashMap<>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
      if (field.isAnnotationPresent(Column.class)) {
        /**
         *      
         */
        Column declaredAnnotation = field.getDeclaredAnnotation(Column.class);
        String column = declaredAnnotation.name();
        map.put("fieldNames", field.getName());
        map.put("column", column);
        break;
      }
    }
    return map;
  }
 
  /**
   *        @Table       
   *
   * @param clazz
   * @return
   */
  public static Map<String, String> getTableName(Class<?> clazz) {
    Map<String, String> map = new ConcurrentHashMap<>();
    Table annotation = clazz.getAnnotation(Table.class);
    String name = annotation.name();
    String className = clazz.getSimpleName();
    map.put("tableName", name);
    map.put("className", className);
    return map;
  }
}



이상 의 이 편 은 JAVA 반 사 를 이용 하여 데이터베이스 테이블 이름 을 읽 고 대응 하 는 실체 클래스 를 자동 으로 생 성 하 는 작업 은 바로 편집장 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.여러분 에 게 참고 가 될 수 있 고 여러분 들 이 저 희 를 많이 지지 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기