Recently contacted a job similar to the Code generation tool. The idea is to get the field and field type of the class through the reflection mechanism of Java,
This allows you to create a map collection that stores the table name (a special structure string determined by the class name), a table field (determined by a class variable), a table field type (determined by the variable type), and DAO that invokes the stored Procedure generation table in MyBatis by passing the map to MyBatis.
1, add a stored procedure to the database as follows
Sp_createtable
BEGIN DECLARESql_textVARCHAR( -); DROP TABLE IF EXISTSP_name; SETSql_text=CONCAT ('CREATE TABLE', P_NAME,P_FIELDSTR); SELECTSql_text; SET @sql_text=Sql_text; PREPAREstmt from @sql_text; EXECUTEstmt; deallocate PREPAREstmt; END
The SQL statements in 2,mybatis are as follows:
< Select id="CreateTable" parametertype="Java.util.Map" resulttype="String" > Call sp_createtable (#{name},#{fields}) </Select>
Methods in 3,dao
Public void createtable (map<string, string> Map);
4, Generate the field list and type through Java reflection:
PublicMap<string, string>createtable (modelenum model, String className) {Try{Class<?> clazz = Class.forName ("Com.me.info." +className); Field[] F =Clazz.getdeclaredfields (); String TableName=gettablename (model, className); Map<string, string> map =NewHashmap<string, string>(); String SQL= ""; for(inti = 0; i < f.length; i++) {Field field=F[i]; String Paramtype=setparamtertype (field); String param=Field.getname (); if(Param.equals ("id") ) {SQL+ = "(" + param + "" + Paramtype + "PRIMARY KEY not NULL,";//primary Key ";}Else{SQL+ = param + "+ paramtype +", "; }} SQL= sql.substring (0, Sql.length ()-1); SQL+= ")"; Map.put ("Name", TableName); Map.put ("Fields", SQL); returnmap; } Catch(Exception e) {e.printstacktrace (); } return NULL; }
5. method to get the field type: Setparamtertype
Private StaticString Setparamtertype (Field f)throwsException {if(("int"). Equals (F.gettype (). Getcanonicalname ())) {return"Int (11)"; } Else if("Long"). Equals (F.gettype (). Getcanonicalname ())|| ("Java.lang.Long"). Equals (F.gettype (). Getcanonicalname ())) {return"Int (11)"; } Else if("Float"). Equals (F.gettype (). Getcanonicalname ())) {return"Float (10)"; } Else if(("float[]"). Equals (F.gettype (). Getcanonicalname ())) {return"varchar (255)"; } Else if("Java.lang.String"). Equals (F.gettype (). Getcanonicalname ())) {return"varchar (255)"; } Else if(("java.lang.long[]"). Equals (F.gettype (). Getcanonicalname ())) {return"varchar (255)"; } Else if(("int[]"). Equals (F.gettype (). Getcanonicalname ())) {return"varchar (255)"; } return NULL; }
If you are in a hurry and have omissions or mistakes in your arrangement, please correct me.
Application of Java reflection +mybatis+spring dynamically generated database tables