您的位置:首页 > 编程语言

分享一份自己写的关于ssh框架自动生成Bean的源代码和思路

2017-07-27 21:36 531 查看
一开始是想mybatis有自动生成bean的工具,但hibernate却没有或者是我没接触到,就想利用反射机制实现由表到实体类自动生成的工具类,但其实这个方式行不通,java的反射机制虽然强大,但也没办法无中生有。于是在网上搜了下,发现已经有前辈写过这类工具类,使用的是io流,直接创建.java文件 具体的代码如下希望不足之处可以得到大家的提点

首先是处理字符串的工具类:

import java.io.PrintWriter;

import com.cxb.myexception.IllegalException;

/**

 * 字符串处理

 * @author MrChen

 *

 */

public class StringUtil {

    /**

     * 将set方法写入流中

     * @param writer    目标流

     * @param columnName    数据库字段名

     * @param type    数据类型 java类型

     * @throws IllegalException

     */

     public static void gainSetMethod(PrintWriter writer,String columnName,String type)throws IllegalException{

         String beanName=StringUtil.gainBeanString(columnName);

         char[] ch = beanName.toCharArray();  

         if (ch[0] >= 'a' && ch[0] <= 'z') {  

             ch[0] = (char) (ch[0] - 32);  

         }

         writer.println("\tpublic void set"+new String(ch)+"("+type+" "+beanName+"){");

         writer.println("\t\t this."+beanName+"="+beanName+";\n\t}");

     }

    /**

     * 将get方法写入流中

     * @param writer    目标流

     * @param columnName    数据库字段名

     * @param type    数据类型 java类型

     * @throws IllegalException

     */

     public static void gainGetMethod(PrintWriter writer,String columnName,String type)throws IllegalException{

         String beanName=StringUtil.gainBeanString(columnName);

         char[] ch = beanName.toCharArray();  

         if (ch[0] >= 'a' && ch[0] <= 'z') {  

             ch[0] = (char) (ch[0] - 32);  

         }

         writer.println("\tpublic "+type+" get"+new String(ch)+"(){");

         writer.println("\t\treturn this."+beanName+";\n\t}");

     }

    /**

     * 根据_将表名转为首字母大写的ClassName

     * @param tableName    表名     WORD_WORD or T_WORD_WORD

     * @return

     * @throws IllegalException

     */

    public static String gainClassNameString(String tableName) throws IllegalException{

        return StringUtil.gainBeanString(tableName, "_", 1);

    }

    /**

     * 根据_将数据库字段转为驼峰法的Bean字段

     * @param columnName    数据库字段    WORD_WORD or T_WORD_WORD

     * @return

     * @throws IllegalException

     */

    public static String gainBeanString(String columnName)throws IllegalException{

        return StringUtil.gainBeanString(columnName, "_", 0);

    }

    /**

     * 根据正则表达式分离字段并拼接为驼峰法命名的Bean字段或首字母大写的className字段

     * @param tableString

     * @param regex

     * @param type 0-BeanName !0-ClassName

     * @return

     * throws IllegalException

     */

    public static String gainBeanString(String tableString,String regex,int type)throws IllegalException{

        try{

            if(tableString==null||"".equals(tableString)){

                throw new IllegalException("字符不能为null");

            }

            String[] words=tableString.split(regex);//根据下划线讲字段分离

            if(words.length<=0){

                throw new IllegalException("非法数据库命名");

            }

            if(words.length==1){

                if(type==0){

                    return words[0].toLowerCase();

                }else{

                    return StringUtil.initialString(words[0]);

                }

            }

            StringBuilder targetStr=new StringBuilder();

            //拼接首个字段

            int firstInt=0;

            if(words[0].equalsIgnoreCase("T"))

                firstInt=1;

            if(type==0){

                targetStr.append(words[firstInt].toLowerCase());

            }else{

                targetStr.append(StringUtil.initialString(words[firstInt]));

            }

            //拼接其余字段

            for (int i = firstInt+1; i < words.length; i++) {

                targetStr.append(StringUtil.initialString(words[i]));

            }

            return targetStr.toString();

        }catch(IllegalException e){

            e.printStackTrace();

            throw new IllegalException("非法字符:"+tableString);

        }

    }

    /**

     * 返回一个首字母大写的字符串

     * @param str

     * @return

     */

    public static String initialString(String str)throws IllegalException{

        try{

            str=str.toLowerCase();

            char[] ch = str.toCharArray();  

            if (ch[0] >= 'a' && ch[0] <= 'z') {  

                ch[0] = (char) (ch[0] - 32);  

            }

            return new String(ch);

        }catch(Exception e){

            e.printStackTrace();

            throw new IllegalException("字符首字母转换异常:"+str);

        }

    }

}

----------------------------------------------------------生成Bean工具类---------------------------------------------------

package    com.cxb.util;

import java.io.File;

import java.io.PrintWriter;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

import java.util.Date;

import javax.annotation.Resource;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.SequenceGenerator;

import javax.persistence.Table;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.transform.Transformers;

import org.springframework.stereotype.Component;

import org.springframework.stereotype.Repository;

import org.springframework.transaction.annotation.Transactional;

/**

 * 根据数据库表自动生成Bean

 * @author MrChen

 *

 */

@Transactional

@Component(value="createBean")

public class CreateBean {

    @Resource(name = "sessionFactory")

    private SessionFactory sessionFactory;

    private String packagePath="\\src\\main\\java\\com\\cxb\\model";//生成的包路径

    /**

     * @param userName    数据库用户名

     * @param packageStr    生成的Bean所在目录

     * @return

     */<
4000
br />
    public int createBean(String userName,String packageStr){

        try{

            String directory=System.getProperty("user.dir");

            directory+="\\src\\main\\java\\"+packageStr;

            directory=directory.toLowerCase();

            System.out.println(directory);

            //生成路径

            new File(directory).mkdirs();

            //获取所有表名

            StringBuilder sql=new StringBuilder();

            sql.append("select table_name from user_tables t");

            if(userName!=null){

                sql.append(" where t.TABLESPACE_NAME='");

                sql.append(userName.toUpperCase());

                sql.append("'");

            }

            System.out.println(sql);

            //获取当前用户下的所有表名

            List<String> tableName=getSession().createSQLQuery(sql.toString()).list();

            int tableSize=0;

            System.out.println("当期共获取表名:"+tableName.size());

            for (String string : tableName) {

                try{

                    //排除工作流表

                    if(string.toUpperCase().startsWith("ACT"))

                        continue;

                    List<Map<String, Object>> temp=findTableDesc(string);

                    //创建.java文件

                    String tempUrl=directory+"\\"+StringUtil.gainClassNameString(string)+".java";

                    File file=new File(tempUrl);

                    file.createNewFile();

                    PrintWriter write=new PrintWriter(file,"UTF-8");

                    //写入所属空间

                    write.println("package\t"+packageStr.toLowerCase().replaceAll("\\\\", ".")+";");

                    //导入包

                    write.println("import\tjavax.persistence.Column;");

                    write.println("import\tjavax.persistence.Entity;");

                    write.println("import\tjavax.persistence.GeneratedValue;");

                    write.println("import\tjavax.persistence.GenerationType;");

                    write.println("import\tjavax.persistence.Id;");

                    write.println("import\tjavax.persistence.SequenceGenerator;");

                    write.println("import\tjavax.persistence.Table;");

                    write.println("import\tjava.util.Date;");

                    //写入类及类主键

                    write.println("@Entity\n@Table(name=\""+string+"\")\npublic class "+StringUtil.gainClassNameString(string)+"{\n");

                    //写入主键

                    write.println("\tprivate Integer "+StringUtil.gainBeanString((String)temp.get(0).get("COLUMN_NAME"))+";");

                    //写入get&set方法

                    write.println("\t@Id");

                    if(temp.get(0).get("NULLABLE").equals("N")){

                        write.println("\t@SequenceGenerator(name=\"seq_generator\",sequenceName=\"table_id\",  allocationSize = 1)");

                        write.println("\t@GeneratedValue(generator=\"seq_generator\",strategy=GenerationType.SEQUENCE)");

                    }

                    write.println("\t@Column(name=\""+temp.get(0).get("COLUMN_NAME")+"\")");

                    StringUtil.gainGetMethod(write, (String)temp.get(0).get("COLUMN_NAME"), "Integer");

                    StringUtil.gainSetMethod(write, (String)temp.get(0).get("COLUMN_NAME"), "Integer");

                    //写入其他字段

                    for (int i = 1; i < temp.size(); i++) {

                        //获取数据类型

                        String type="";

                        switch((String)temp.get(i).get("DATA_TYPE")){

                        case "NUMBER":

                        case "Integer":

                            type="Integer";

                            break;

                        case "NVARCHAR2":

                        case "VARCHAR2":

                        case "VARCHAR":

                            type="String";

                            break;

                        case "TIMESTAMP(6)":

                        case "TIMESTAMP(3)":

                        case "DATE":

                            type="Date";

                            break;

                        default:

                            type="String";

                            break;

                        }

                        write.println("\tprivate "+type+" "+StringUtil.gainBeanString((String)temp.get(i).get("COLUMN_NAME"))+";");

                        write.println("\t@Column(name=\""+temp.get(i).get("COLUMN_NAME")+"\")");

                        StringUtil.gainGetMethod(write, (String)temp.get(i).get("COLUMN_NAME"), type);

                        StringUtil.gainSetMethod(write, (String)temp.get(i).get("COLUMN_NAME"), type);

                    }

                    write.print("}");

                    write.flush();

                }catch(Exception e){

                    System.err.println(string+"表创建Bean失败"+(++tableSize));

                }

            }

        }catch(Exception e){

            e.printStackTrace();

        }

        return 0;

    }

    /**

     * 构建get/set方法

     */

    public void createSetAndGet(PrintWriter writer,String FieldName){

    }

    /**

     * 获取表结构

     * @return

     */

    public List<Map<String, Object>> findTableDesc(String tableName){

        return getSession().createSQLQuery("select COLUMN_NAME,DATA_TYPE,NULLABLE from user_tab_columns where Table_Name='"+tableName+"'").setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();

    }

    public Session getSession() {

        return this.sessionFactory.getCurrentSession();

        // .getCurrentSession();

    }

    public SessionFactory getSessionFactory() {

        return sessionFactory;

    }

    public void setSessionFactory(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐