我喜欢理论和实践相结合....so,今天我试着模仿hibernate的逆向工程,哈哈,我成功啦....

话不多说....直接上图先:

项目结构:

spring data jpa 逆向工程 java逆向工程_List

运行效果:



1 #jdbc.cfg.properties配置文件信息
2 #database name
3 DB_NAME = mytest



spring data jpa 逆向工程 java逆向工程_ci_02

POJO效果:

spring data jpa 逆向工程 java逆向工程_List_03



#jdbc.cfg.properties配置文件信息
#database name
DB_NAME = hongten



spring data jpa 逆向工程 java逆向工程_ci_04

运行效果:

spring data jpa 逆向工程 java逆向工程_ci_05



//说明:我们生成的POJO类的getter,setter方法没有自动生成,需要我们手动生成...^_^
//===============================================



====================================================

代码部分:

====================================================

/hibernate_reverse/src/com/b510/db/util/DBUtil.java



1 /**
  2  * 
  3  */
  4 package com.b510.db.util;
  5 
  6 import java.sql.Connection;
  7 import java.sql.DriverManager;
  8 import java.sql.PreparedStatement;
  9 import java.sql.ResultSet;
 10 import java.util.ArrayList;
 11 import java.util.List;
 12 
 13 import org.apache.log4j.Logger;
 14 
 15 import com.b510.velocity.util.DescTableBean;
 16 import com.b510.velocity.util.LoadProperties;
 17 
 18 /**
 19  * 数据库工具,该类功能:<br>
 20  * <li>showTables()获取数据库的所有表信息</li>
 21  * <li>descTable()获取表的描述信息</li>
 22  * <br>********************************************<br>
 23  * <code>jdbc.cfg.properties</code>为数据库的配置信息,默认位置是在项目src目录下面<br>
 24  * @author Hongten
 25  * @date 2013-4-9
 26  */
 27 public class DBUtil {
 28     Logger log = Logger.getLogger(DBUtil.class);
 29 
 30     // 载入配置
 31     // ==================================
 32     private static final String JDBC_CFG_PROPERTIES = "jdbc.cfg.properties";
 33     private static LoadProperties loadProperties = new LoadProperties(JDBC_CFG_PROPERTIES);
 34 
 35     // JDBC RESOURCES
 36     // ==================================
 37     private static String DB_DRIVER = loadProperties.getValue("DB_DRIVER");
 38     private static String DB_NAME = loadProperties.getValue("DB_NAME");
 39     private static String DB_PASSWORD = loadProperties.getValue("DB_PASSWORD");
 40     private static String DB_USER_NAME = loadProperties.getValue("DB_USER_NAME");
 41     private static String DB_URL = "jdbc:mysql://localhost:" + loadProperties.getValue("DB_PORT") + "/" + DB_NAME;
 42     private static String SHOW_TABLES = "show tables";
 43     
 44     /**
 45      * 读取配置文件,初始化信息
 46      */
 47     public DBUtil() {
 48         loadProperties = loadProperties == null ? new LoadProperties(JDBC_CFG_PROPERTIES) : loadProperties;
 49     }
 50 
 51     /**
 52      * 获取数据库中所有的表名称
 53      * 
 54      * @return 数据库中表名称的list
 55      * @throws Exception
 56      */
 57     public List<String> showTables() throws Exception {
 58         List<String> list = new ArrayList<String>();
 59         Class.forName(DB_DRIVER);
 60         Connection conn = DriverManager.getConnection(DB_URL, DB_USER_NAME, DB_PASSWORD);
 61         PreparedStatement ps = conn.prepareStatement(SHOW_TABLES);
 62         ResultSet rs = ps.executeQuery();
 63         log.info("数据库:[" + DB_NAME + "]中的表如下:");
 64         while (rs.next()) {
 65             String tableName = rs.getString(1);
 66             log.info(tableName);
 67             list.add(tableName);
 68         }
 69         close(rs, ps, conn);
 70         return list;
 71     }
 72 
 73     /**
 74      * 获取表的描述
 75      * @param tableName 表名称
 76      * @return
 77      * @throws Exception
 78      */
 79     public List<DescTableBean> descTable(String tableName) throws Exception {
 80         List<DescTableBean> list = new ArrayList<DescTableBean>();
 81         DescTableBean temp = null;
 82         Class.forName(DB_DRIVER);
 83         Connection conn = DriverManager.getConnection(DB_URL, DB_USER_NAME, DB_PASSWORD);
 84         PreparedStatement ps = conn.prepareStatement("desc " + tableName);
 85         ResultSet rs = ps.executeQuery();
 86         log.info("获取数据库表:[" + tableName + "]的结构:");
 87         while (rs.next()) {
 88             String descTable = " " + rs.getString(1) + "   " + rs.getString(2) + "    " + rs.getString(3) + "        " + rs.getString(4) + "        " + rs.getString(5) + "      " + rs.getString(6);
 89             log.info(descTable);
 90             temp = new DescTableBean();
 91             temp.setField(rs.getString(1));
 92             String type = rs.getString(2);
 93             temp.setType(getType(type));
 94             temp.setLength(Integer.valueOf(getValueByType(type)));
 95             temp.setDecase(Integer.valueOf(getDecase(type)));
 96             temp.setIsNull(rs.getString(3));
 97             temp.setKey(rs.getString(4));
 98             temp.setDefaultValue(rs.getString(5));
 99             temp.setExtra(rs.getString(6));
100             list.add(temp);
101         }
102         close(rs, ps, conn);
103         return list;
104     }
105     
106     /**
107      * 关闭:记录集,声明,链接对象
108      * @param rs 记录集
109      * @param ps 声明
110      * @param conn 链接对象
111      * @throws Exception
112      */
113     protected void close(ResultSet rs,PreparedStatement ps,Connection conn) throws Exception{
114         if (rs != null) {
115             rs.close();
116         }
117         if (ps != null) {
118             ps.close();
119         }
120         if (conn != null) {
121             conn.close();
122         }
123     }
124     
125     /**
126      * 获取类型
127      * @param type 如:<code>varchar(20)</code>,<code>datetime</code>,<code>double</code>,<code>longtext</code>
128      * @return 结果:<br><li>type = "varchar(20)", return type = "varchar";</li>
129      *            <li>type = "datetime", return type = "datetime";</li>
130      */
131     protected String getType(String type){
132         if(type.endsWith(")")){
133             type = type.substring(0, type.indexOf("("));
134         }
135         return type;
136     }
137     
138     /**
139      * 获取类型的长度,默认为255
140      * @param type 如:<code>varchar(20)</code>,<code>decimal(19,2)</code>,<code>datetime</code>,<code>double</code>,<code>longtext</code>
141      * @return 结果:<br><li>type = "varchar(20)", return "20";</li>
142      *            <li>type = "datetime", return type = "255";</li>
143      *            <li>type = "decimal(19,2)", return type = "19";</li>
144      */
145     protected String getValueByType(String type) {
146         if (type.endsWith(")")) {
147             type = type.substring(type.indexOf("(") + 1, type.length() - 1);
148             if(type.contains(",")){
149                 type = type.substring(0,type.indexOf(","));
150             }
151             return type;
152         } else {
153             return "255";
154         }
155     }
156     
157     /**
158      * 获取十进位,默认为0
159      * @param type 如:<code>varchar(20)</code>,<code>decimal(19,2)</code>,<code>datetime</code>,<code>double</code>,<code>longtext</code>
160      * @return 结果:<br><li>type = "varchar(20)", return "0";</li>
161      *            <li>type = "datetime", return type = "255";</li>
162      *            <li>type = "decimal(19,2)", return type = "19";</li>
163      */
164     protected String getDecase(String type){
165         if (type.endsWith(")")) {
166             type = type.substring(type.indexOf("(") + 1, type.length() - 1);
167             if(type.contains(",")){
168                 type = type.substring(type.indexOf(",") + 1, type.length());
169             }else{
170                 type = "0";
171             }
172             return type;
173         } else {
174             return "0";
175         }
176     }
177 
178     
179 /*    public static void main(String[] args) throws Exception {
180         DBUtil dbUtil = new DBUtil();
181         List<String> list = dbUtil.showTables();
182         for (String str : list) {
183             System.out.println(str);
184             List<DescTableBean> listd = dbUtil.descTable(str);
185             for(DescTableBean d : listd){
186                 System.out.println(d.getField()+d.getLength()+d.getDecase()+d.getType()+d.getIsNull()+d.getKey()+d.getDefaultValue()+d.getExtra());
187             }
188         }
189     }*/
190 }



/hibernate_reverse/src/com/b510/reverse/test/HibernateReverseTest.java



1 /**
 2  * 
 3  */
 4 package com.b510.reverse.test;
 5 
 6 import java.util.List;
 7 
 8 import com.b510.db.util.DBUtil;
 9 import com.b510.velocity.util.DescTableBean;
10 import com.b510.velocity.util.VelocityUtil;
11 
12 /**
13  * 测试类,运行该类,在刷新一下项目,就可以获得我们的POJO类啦
14  * @author Hongten
15  * @date 2013-4-9
16  */
17 public class HibernateReverseTest {
18     public static void main(String[] args) throws Exception {
19         VelocityUtil velocityUtil = new VelocityUtil();
20         DBUtil dbUtil = new DBUtil();
21         List<String> list = dbUtil.showTables();
22         for (String tableName : list) {
23             System.out.println(tableName);
24             List<DescTableBean> descTable = dbUtil.descTable(tableName);
25             velocityUtil.generateBean(tableName, descTable);
26         }
27     }
28 }



/hibernate_reverse/src/com/b510/velocity/util/Annotation.java



1 package com.b510.velocity.util;
 2 
 3 /**
 4  * 注释
 5  * 
 6  * @author hongten<br>
 7  * @date 2013-3-10
 8  */
 9 public class Annotation {
10 
11     /**
12      * 作者名称
13      */
14     private String authorName;
15     /**
16      * 作者邮箱
17      */
18     private String authorMail;
19     /**
20      * 日期
21      */
22     private String date;
23     /**
24      * 版本
25      */
26     private String version;
27 
28     public String getAuthorName() {
29         return authorName;
30     }
31 
32     public void setAuthorName(String authorName) {
33         this.authorName = authorName;
34     }
35 
36     public String getAuthorMail() {
37         return authorMail;
38     }
39 
40     public void setAuthorMail(String authorMail) {
41         this.authorMail = authorMail;
42     }
43 
44     public String getDate() {
45         return date;
46     }
47 
48     public void setDate(String date) {
49         this.date = date;
50     }
51 
52     public String getVersion() {
53         return version;
54     }
55 
56     public void setVersion(String version) {
57         this.version = version;
58     }
59 
60 }



/hibernate_reverse/src/com/b510/velocity/util/Bean.java



1 package com.b510.velocity.util;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 
  6 /**
  7  * bean类
  8  * 
  9  * @author hongten<br>
 10  * @date 2013-3-10
 11  */
 12 @SuppressWarnings("rawtypes")
 13 public class Bean {
 14 
 15     /** bean 名称 */
 16     private String name;
 17     /** bean 首字母小写名称 */
 18     private String lowerName;
 19     /** bean 路径 */
 20     private String beanUrl;
 21     /** dao 路径 */
 22     private String beanDaoUrl;
 23     /** dao 实现路径 */
 24     private String beanDaoImplUrl;
 25     /** service 路径 */
 26     private String beanServiceUrl;
 27     /** service 实现路径 */
 28     private String beanServiceImplUrl;
 29     /** web Action 路径 */
 30     private String webActionUrl;
 31     /** web Admin Action 路径 */
 32     private String webAdminActionUrl;
 33 
 34     private List<Class> beanDaoList = new ArrayList<Class>();
 35     private List<Class> beanDaoImplList = new ArrayList<Class>();
 36     private List<Class> beanServiceList = new ArrayList<Class>();
 37     private List<Class> beanServiceImplList = new ArrayList<Class>();
 38 
 39     private static List<String> beanDaoUrlList = new ArrayList<String>();
 40     private static List<String> beanDaoImplUrlList = new ArrayList<String>();
 41     private static List<String> beanServiceUrlList = new ArrayList<String>();
 42     private static List<String> beanServiceImplUrlList = new ArrayList<String>();
 43 
 44     public String getName() {
 45         return name;
 46     }
 47 
 48     public void setName(String name) {
 49         this.name = name;
 50     }
 51 
 52     public String getLowerName() {
 53         return lowerName;
 54     }
 55 
 56     public void setLowerName(String lowerName) {
 57         this.lowerName = lowerName;
 58     }
 59 
 60     public String getBeanUrl() {
 61         return beanUrl;
 62     }
 63 
 64     public void setBeanUrl(String beanUrl) {
 65         this.beanUrl = beanUrl;
 66     }
 67 
 68     public String getBeanDaoUrl() {
 69         return beanDaoUrl;
 70     }
 71 
 72     public void setBeanDaoUrl(String beanDaoUrl) {
 73         this.beanDaoUrl = beanDaoUrl;
 74     }
 75 
 76     public String getBeanDaoImplUrl() {
 77         return beanDaoImplUrl;
 78     }
 79 
 80     public void setBeanDaoImplUrl(String beanDaoImplUrl) {
 81         this.beanDaoImplUrl = beanDaoImplUrl;
 82     }
 83 
 84     public String getBeanServiceUrl() {
 85         return beanServiceUrl;
 86     }
 87 
 88     public void setBeanServiceUrl(String beanServiceUrl) {
 89         this.beanServiceUrl = beanServiceUrl;
 90     }
 91 
 92     public String getBeanServiceImplUrl() {
 93         return beanServiceImplUrl;
 94     }
 95 
 96     public void setBeanServiceImplUrl(String beanServiceImplUrl) {
 97         this.beanServiceImplUrl = beanServiceImplUrl;
 98     }
 99 
100     public String getWebActionUrl() {
101         return webActionUrl;
102     }
103 
104     public void setWebActionUrl(String webActionUrl) {
105         this.webActionUrl = webActionUrl;
106     }
107 
108     public List<Class> getBeanDaoList() {
109         return beanDaoList;
110     }
111 
112     public void setBeanDaoList(List<Class> beanDaoList) {
113         this.beanDaoList = beanDaoList;
114     }
115 
116     public List<Class> getBeanDaoImplList() {
117         return beanDaoImplList;
118     }
119 
120     public void setBeanDaoImplList(List<Class> beanDaoImplList) {
121         this.beanDaoImplList = beanDaoImplList;
122     }
123 
124     public List<Class> getBeanServiceList() {
125         return beanServiceList;
126     }
127 
128     public void setBeanServiceList(List<Class> beanServiceList) {
129         this.beanServiceList = beanServiceList;
130     }
131 
132     public List<Class> getBeanServiceImplList() {
133         return beanServiceImplList;
134     }
135 
136     public void setBeanServiceImplList(List<Class> beanServiceImplList) {
137         this.beanServiceImplList = beanServiceImplList;
138     }
139 
140     public static List<String> getBeanDaoUrlList() {
141         return beanDaoUrlList;
142     }
143 
144     public static void setBeanDaoUrlList(List<String> beanDaoUrlList) {
145         Bean.beanDaoUrlList = beanDaoUrlList;
146     }
147 
148     public static List<String> getBeanDaoImplUrlList() {
149         return beanDaoImplUrlList;
150     }
151 
152     public static void setBeanDaoImplUrlList(List<String> beanDaoImplUrlList) {
153         Bean.beanDaoImplUrlList = beanDaoImplUrlList;
154     }
155 
156     public static List<String> getBeanServiceUrlList() {
157         return beanServiceUrlList;
158     }
159 
160     public static void setBeanServiceUrlList(List<String> beanServiceUrlList) {
161         Bean.beanServiceUrlList = beanServiceUrlList;
162     }
163 
164     public static List<String> getBeanServiceImplUrlList() {
165         return beanServiceImplUrlList;
166     }
167 
168     public static void setBeanServiceImplUrlList(List<String> beanServiceImplUrlList) {
169         Bean.beanServiceImplUrlList = beanServiceImplUrlList;
170     }
171 
172     public String getWebAdminActionUrl() {
173         return webAdminActionUrl;
174     }
175 
176     public void setWebAdminActionUrl(String webAdminActionUrl) {
177         this.webAdminActionUrl = webAdminActionUrl;
178     }
179 
180 }



/hibernate_reverse/src/com/b510/velocity/util/DescTableBean.java



1 /**
  2  * 
  3  */
  4 package com.b510.velocity.util;
  5 
  6 /**
  7  * 在数据库中,我们可以用sql语句:"desc table_name",查询名称为:"table_name"的表的结构情况<br>
  8  * 这里就是
  9  * 
 10  * @author Hongten
 11  * @date 2013-4-9
 12  */
 13 public class DescTableBean {
 14 
 15     /**
 16      * id编号
 17      */
 18     private Integer id;
 19     /**
 20      * 属性,eg:<code>name</code>
 21      */
 22     private String field;
 23     /**
 24      * 类型,eg:<code>varchar</code>,<code>datetime</code>,<code>double</code>,<code>longtext</code>
 25      */
 26     private String type;
 27     /**
 28      * 长度,如果没有规定长度的,则默认为255
 29      */
 30     private Integer length = 255;
 31     /**
 32      * 十进位,默认为0,针对<code>decimal</code>
 33      */
 34     private Integer decase;
 35     /**
 36      * 是否为空,只有两个选择:YES,NO,eg:<code>YES</code>
 37      */
 38     private String isNull;
 39     /**
 40      * 是否为主键,如果为主键则, key = <code>PRI</code>,如果唯一,则 key = <code>UNI</code>
 41      * ,如果为外键,则 key = <code>MUL</code>
 42      */
 43     private String key;
 44     /**
 45      * 属性的默认值
 46      */
 47     private String defaultValue;
 48     /**
 49      * 其他选项,如一个表的id的增长方式为:auto_increment
 50      */
 51     private String extra;
 52 
 53     public Integer getId() {
 54         return id;
 55     }
 56 
 57     public void setId(Integer id) {
 58         this.id = id;
 59     }
 60 
 61     public String getField() {
 62         return field;
 63     }
 64 
 65     public void setField(String field) {
 66         this.field = field;
 67     }
 68 
 69     public String getType() {
 70         return type;
 71     }
 72 
 73     public void setType(String type) {
 74         this.type = type;
 75     }
 76 
 77     public Integer getLength() {
 78         return length;
 79     }
 80 
 81     public void setLength(Integer length) {
 82         this.length = length;
 83     }
 84 
 85     public String getIsNull() {
 86         return isNull;
 87     }
 88 
 89     public void setIsNull(String isNull) {
 90         this.isNull = isNull;
 91     }
 92 
 93     public String getKey() {
 94         return key;
 95     }
 96 
 97     public void setKey(String key) {
 98         this.key = key;
 99     }
100 
101     public String getDefaultValue() {
102         return defaultValue;
103     }
104 
105     public void setDefaultValue(String defaultValue) {
106         this.defaultValue = defaultValue;
107     }
108 
109     public String getExtra() {
110         return extra;
111     }
112 
113     public void setExtra(String extra) {
114         this.extra = extra;
115     }
116 
117     public Integer getDecase() {
118         return decase;
119     }
120 
121     public void setDecase(Integer decase) {
122         this.decase = decase;
123     }
124 
125 }



/hibernate_reverse/src/com/b510/velocity/util/LoadProperties.java



1 /**
 2  * 
 3  */
 4 package com.b510.velocity.util;
 5 
 6 import java.io.IOException;
 7 import java.io.InputStream;
 8 import java.util.Properties;
 9 
10 import org.apache.log4j.Logger;
11 
12 /**
13  * @author Hongten
14  * @date 2013-4-9
15  */
16 public class LoadProperties {
17 
18     Logger log = Logger.getLogger(LoadProperties.class);
19 
20     private Properties prop = new Properties();
21 
22     public LoadProperties(String propertiesName) {
23         prop = loadProperty(propertiesName);
24     }
25 
26     /**
27      * 载入配置文件
28      * 
29      * @return
30      */
31     public Properties loadProperty(String propertiesName) {
32         try {
33             if (propertiesName != null || !"".equals(propertiesName)) {
34                 InputStream is = LoadProperties.class.getClassLoader().getResourceAsStream(propertiesName);
35                 if (is == null) {
36                     is = LoadProperties.class.getClassLoader().getResourceAsStream("/" + propertiesName);
37                 }
38                 prop.load(is);
39                 is.close();
40                 log.info("载入配置文件:[" + propertiesName + "]成功!");
41             }
42         } catch (IOException e) {
43             log.error("载入配置文件:[" + propertiesName + "]失败!");
44             e.printStackTrace();
45         }
46         return prop;
47     }
48 
49     /**
50      * 根据key值,获取key对应的value
51      * 
52      * @param key
53      *            key值
54      * @param defaultv
55      *            key对应的value
56      * @return
57      */
58     public String getValue(String key, String defaultv) {
59         return prop.getProperty(key, defaultv);
60     }
61 
62     /**
63      * 根据key值,获取key对应的value
64      * 
65      * @param key
66      *            key值
67      * @return
68      */
69     public String getValue(String key) {
70         return prop.getProperty(key);
71     }
72 
73     public static void main(String[] args) {
74         String proPath = "jdbc.cfg.properties";
75         LoadProperties loadProperties = new LoadProperties(proPath);
76         String value = loadProperties.getValue("ANNOTATION_AUTHOR_NAME");
77         System.out.println(value);
78     }
79 
80 }



/hibernate_reverse/src/com/b510/velocity/util/VelocityUtil.java



1 /**
  2  * 
  3  */
  4 package com.b510.velocity.util;
  5 
  6 import java.io.File;
  7 import java.io.FileWriter;
  8 import java.io.StringWriter;
  9 import java.text.SimpleDateFormat;
 10 import java.util.Date;
 11 import java.util.List;
 12 
 13 import org.apache.log4j.Logger;
 14 import org.apache.velocity.Template;
 15 import org.apache.velocity.VelocityContext;
 16 import org.apache.velocity.app.VelocityEngine;
 17 
 18 /**
 19  * 模板工具类,该类功能:<br>
 20  * <li>generateBean()生成java的POJO类</li>
 21  * <br>********************************************<br>
 22  * <code>bean.cfg.properties</code>为数据库的配置信息,默认位置是在项目src目录下面<br>
 23  * @author Hongten
 24  * @date 2013-4-9
 25  */
 26 public class VelocityUtil {
 27 
 28     Logger log = Logger.getLogger(VelocityUtil.class);
 29 
 30     // 载入bean配置
 31     // ===================================
 32     private static final String BEAN_CFG_PROPERTIES = "bean.cfg.properties";
 33     private static LoadProperties beanLoadProperties = new LoadProperties(BEAN_CFG_PROPERTIES);
 34 
 35     // BEAN PROPERTIES
 36     // ===================================
 37     Bean bean = new Bean();
 38     private static String BEAN_URL = beanLoadProperties.getValue("BEAN_URL");
 39     private static String BEAN_PATH = BEAN_URL.replace(".", "/");
 40 
 41     // ANNOTATION
 42     // ====================================
 43     private static Annotation annotation = new Annotation();
 44 
 45     /**
 46      * 读取配置文件,初始化信息
 47      */
 48     public VelocityUtil() {
 49         beanLoadProperties = beanLoadProperties == null ? new LoadProperties(BEAN_CFG_PROPERTIES) : beanLoadProperties;
 50         initAnnotation(beanLoadProperties);
 51     }
 52 
 53     /**
 54      * 初始化注释信息
 55      * 
 56      * @param beanLoadProperties
 57      *            加载配置
 58      */
 59     protected void initAnnotation(LoadProperties beanLoadProperties) {
 60         annotation.setAuthorName(beanLoadProperties.getValue("ANNOTATION_AUTHOR_NAME"));
 61         annotation.setAuthorMail(beanLoadProperties.getValue("ANNOTATION_AUTHOR_MAIL"));
 62         annotation.setVersion(beanLoadProperties.getValue("ANNOTATION_VERSION"));
 63         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 64         annotation.setDate(simpleDateFormat.format(new Date()));
 65     }
 66 
 67     /**
 68      * 根据模板生成代码
 69      * 
 70      * @param fileVMPath
 71      *            模板路径
 72      * @param bean
 73      *            目标bean
 74      * @param annotation
 75      *            注释
 76      * @param descTable
 77      *            表描述
 78      * @return
 79      * @throws Exception
 80      */
 81     public String createCode(String fileVMPath, Bean bean, Annotation annotation, List<DescTableBean> descTable) throws Exception {
 82         VelocityEngine velocityEngine = new VelocityEngine();
 83         velocityEngine.setProperty("input.encoding", "UTF-8");
 84         velocityEngine.setProperty("output.encoding", "UTF-8");
 85         velocityEngine.init();
 86         Template template = velocityEngine.getTemplate(fileVMPath);
 87         VelocityContext velocityContext = new VelocityContext();
 88         velocityContext.put("bean", bean);
 89         velocityContext.put("annotation", annotation);
 90         velocityContext.put("descTable", descTable);
 91         StringWriter stringWriter = new StringWriter();
 92         template.merge(velocityContext, stringWriter);
 93         return stringWriter.toString();
 94     }
 95 
 96     /**
 97      * 生成java bean文件
 98      * 
 99      * @param tableName
100      *            表名称,这里会映射成bean的名称
101      * @param descTable
102      *            表描述
103      * @throws Exception
104      */
105     public void generateBean(String tableName, List<DescTableBean> descTable) throws Exception {
106         if (descTable != null) {
107             String path = System.getProperty("user.dir") + "/src/" + BEAN_PATH + "/";
108             File filePath = new File(path);
109             if (!filePath.exists()) {
110                 filePath.mkdirs();
111                 log.info("创建路径[" + path + "]成功!");
112             }
113             String fileName = path + handleTableName(tableName) + ".java";
114             File file = new File(fileName);
115             FileWriter fw = new FileWriter(file);
116 
117             bean.setName(handleTableName(tableName));
118             bean.setBeanUrl(BEAN_URL);
119             bean.setLowerName(tableName);
120 
121             fw.write(createCode(beanLoadProperties.getValue("BEAN_TEMPLATE_VM_PATH"), bean, annotation, descTable));
122             fw.flush();
123             fw.close();
124         }
125     }
126 
127     /**
128      * 字符串处理
129      * 
130      * @param tableName
131      *            需要被处理的字符串
132      * @return <li>
133      *         <code>tableName = "expert_user_admin"; <br>return "ExpertUserAdmin";</code>
134      *         </li> <li><code>tableName = "expert"; <br>return "Expert";</code>
135      *         </li>
136      */
137     protected String handleTableName(String tableName) {
138         if (tableName.contains("_")) {
139             String[] array = tableName.split("_");
140             String temp = "";
141             for (String str : array) {
142                 temp = temp + str.substring(0, 1).toUpperCase() + str.substring(1);
143             }
144             return temp;
145         } else {
146             return tableName.substring(0, 1).toUpperCase() + tableName.substring(1);
147         }
148     }
149 
150     /*public static void main(String[] args) throws Exception{
151         VelocityUtil velocityUtil = new VelocityUtil();
152         DBUtil dbUtil = new DBUtil();
153         List<String> list = dbUtil.showTables();
154         for (String tableName : list) {
155             System.out.println(tableName);
156             List<DescTableBean> descTable = dbUtil.descTable(tableName);
157             velocityUtil.generateBean(tableName, descTable);
158         }
159     }*/
160 
161 }



/hibernate_reverse/src/vms/bean.vm



1 package ${bean.beanUrl};
 2 
 3 import java.util.Date;
 4 import java.math.BigDecimal;
 5 
 6 import javax.persistence.Column;
 7 import javax.persistence.Entity;
 8 import javax.persistence.GeneratedValue;
 9 import javax.persistence.Id;
10 import javax.persistence.Table;
11 import javax.persistence.Temporal;
12 import javax.persistence.TemporalType;
13 
14 /**
15  * ${bean.name} 实体类
16  * @author <a href="mailto:$!{annotation.authorMail}">$!{annotation.authorName}</a>
17  * @date $!{annotation.date}
18  *
19  * @version $!{annotation.version}
20  *
21  */
22 @Entity
23 @Table(name = "${bean.lowerName}")
24 public class ${bean.name} {
25 
26 #set($_int = "int")
27 #set($_varchar = "varchar")
28 #set($_datetime = "datetime")
29 #set($_decimal = "decimal")
30 #set($_tinyint = "tinyint")
31 #set($_longtext = "longtext")
32 ##foreach begin
33 ##################################################
34 #foreach ( $descTableBean in $descTable )
35 #set($type = $descTableBean.type)
36 ##处理int,转换为java.lang.Integer
37 ##################################################
38 #if($type == $_int)
39     private Integer ${descTableBean.field};
40 #end
41 ##处理varchar,转换为java.lang.String
42 ##################################################
43 #if($type == $_varchar)
44     private String ${descTableBean.field};
45 #end
46 ##处理datetime,转换为java.util.Date
47 ##################################################
48 #if($type == $_datetime)
49     private Date ${descTableBean.field};
50 #end
51 ##处理decimal,转换为java.math.BigDecimal
52 ##################################################
53 #if($type == $_decimal)
54     private BigDecimal ${descTableBean.field};
55 #end
56 ##处理longtext,转换为java.lang.String
57 ##################################################
58 #if($type == $_longtext)
59     private String ${descTableBean.field};
60 #end
61 ##处理tinyint,转换为int
62 ##################################################
63 #if($type == $_tinyint)
64     private int ${descTableBean.field};
65 #end
66 #end
67 }



/hibernate_reverse/src/bean.cfg.properties



1 #########################################################
 2 ##  the template files path
 3 #########################################################
 4 #the bean template file path
 5 BEAN_TEMPLATE_VM_PATH = src/vms/bean.vm
 6 
 7     
 8 #########################################################
 9 ##  the packages
10 #########################################################
11 #the bean UniformResourceLocator
12 BEAN_URL = com.b510.core.bean
13 
14 
15 #########################################################
16 ##  the annotation information
17 #########################################################
18 #the author's name in the annotation
19 ANNOTATION_AUTHOR_NAME = hongten
20 
21 #the author's mail in the annotation
22 ANNOTATION_AUTHOR_MAIL = hongtenzone@foxmail.com
23 
24 #the version of the program in the annotation
25 ANNOTATION_VERSION = 1.0



/hibernate_reverse/src/jdbc.cfg.properties



1 #jdbc driver
 2 DB_DRIVER = com.mysql.jdbc.Driver
 3 
 4 #database name
 5 DB_NAME = mytest
 6 
 7 #jdbc chartacter encoding
 8 DB_CHARACTER_ENCODING = UTF-8
 9 
10 #jdbc database port
11 DB_PORT = 3306
12 
13 #jdbc url eg:<code>jdbc:mysql://localhost:3306/sample?characterEncoding=UTF-8</code>
14 #DB_URL = jdbc:mysql://localhost:3306
15 
16 #jdbc user name
17 DB_USER_NAME = root
18 
19 #jdbc password
20 DB_PASSWORD = root



/hibernate_reverse/src/log4j.properties



1 log4j.appender.current=org.apache.log4j.ConsoleAppender
 2 log4j.appender.current.Target=System.out
 3 log4j.appender.current.layout=org.apache.log4j.PatternLayout
 4 log4j.appender.current.layout.ConversionPattern=[apple] %d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c:%L - %m%n
 5 
 6 log4j.appender.hongten.log=org.apache.log4j.DailyRollingFileAppender
 7 log4j.appender.hongten.log.File=E:\\log4j\\log4j-reverse
 8 log4j.appender.hongten.log.DatePattern='_'yyyy-MM-dd'.log'
 9 log4j.appender.hongten.log.layout=org.apache.log4j.PatternLayout 
10 log4j.appender.hongten.log.layout.ConversionPattern=[apple] %d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c:%L - %m%n
11 
12 log4j.rootLogger=debug,current,hongten.log
13 
14 log4j.logger.org.hibernate.type=error



所需Jar包:

spring data jpa 逆向工程 java逆向工程_java_06

在“为大家提供一个完整的Hibernate Annotation项目_源码下载”中可以下载到hibernate相关jar文件;

在“利用Velocity自动生成自定义代码_java版_源码下载”中可以下载到velocity的相关jar文件;