逆向工程vgenerator(二)
前言
接上篇,这一篇主要的工具类和工厂类,包括数据库方法、通用方法,三个工厂。
常量
/**
*author vvxtoys
*默认xml开头
*文档分隔
*默认方法名
*/
package cc.vvxtoys.utils;
public class Vconst {
public static final String DEFAULT_XML_ROOT = "mapper";
public static final String DEFAULT_XML_PUBLICID = "-//mybatis.org//DTD Mapper 3.0//EN";
public static final String DEFAULT_XML_SYSTEMID = "http://mybatis.org/dtd/mybatis-3-mapper.dtd";
public static final String [] ROOTELEMENT = new String[1];//根标签
public static final String SPACE = " ";
public static final String LINE = "\n";
public static final String TAB = "\t";
public static final String TTAB = "\t\t";
public static final String END = ";";
public static final String SPLIT = "\n\n";
public static final String insert = "insert";
public static final String insert1 = "insertSelective";
public static final String select = "selectByPrimaryKey";
public static final String delete = "deleteByPrimaryKey";
public static final String update = "updateByPrimaryKey";
public static final String update1 = "updateByPrimaryKeySelective";
}
公用
package cc.vvxtoys.utils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import cc.vvxtoys.factory.XMLFactory;
public class Common {
//查找文件
public static String searchAbsolutePath(String filename) {
String absolutePath = "";
LinkedList<File> list = new LinkedList<File>();
try{
File src = new File(".\\src");
File file = new File(src.getCanonicalPath());
File [] files = file.listFiles();
for(int i=0;i<files.length;i++){
list.add(files[i]);
if(files[i].getAbsolutePath().endsWith(filename)){
absolutePath = files[i].getAbsolutePath();
return absolutePath;
}
}
while(!list.isEmpty()){
File tmp = list.removeFirst();
if(tmp.isDirectory()){
File [] fs = tmp.listFiles();
for(int j=0;j<fs.length;j++){
File f = fs[j];
if(f==null){
continue;
}
list.add(fs[j]);
}
}
if(tmp.getAbsolutePath().endsWith(filename)){
absolutePath = tmp.getAbsolutePath();
return absolutePath;
}
}
}catch(Exception e){
e.printStackTrace();
}
return absolutePath;
}
//首字母大写
public static String upInitials(String str){
return str.substring(0,1).toUpperCase()+str.substring(1);
}
public static void writeFile(String filePath, String str) {
try {
FileWriter fw = new FileWriter(new File(filePath), true);
PrintWriter pw = new PrintWriter(fw);
pw.println(str);
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//xml拼接属性
public static String ConcatAttr(String name,String value){
String template = " "+name+"="+"\""+value+"\"";
return template;
}
}
数据库操作
/**
*author vvxtoys
*mysql数据库连接
*获取所有表
*获取所有列
*获取主键
*/
package cc.vvxtoys.config;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cc.vvxtoys.factory.XMLFactory;
public class DB {
private String url;
private String name;
private String user;
private String pass;
public Connection conn = null;
public PreparedStatement pst = null;
private static final String DEFAULT_URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
private static final String DEFAULT_NAME = "com.mysql.jdbc.Driver";
private static final String DEFAULT_USER = "root";
private static final String DEFAULT_PASS = "root";
private DB() {
}
public static DB getInstance() {
DB db = new DB();
db.setName(Engine.name);
db.setPass(Engine.pass);
db.setUrl(Engine.url);
db.setUser(Engine.user);
db.Connection();
return db;
}
private void Connection(){
try{
Class.forName(name);
conn=DriverManager.getConnection(url,user,pass);
}catch(Exception e){
e.printStackTrace();
}
}
public List<String> getTables(){
List<String> tables = new ArrayList<String>();
try{
if(conn!=null){
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet res = dbmd.getTables(null, null, null, new String[]{"TABLE"});
while (res.next()) {
tables.add(res.getString(3));
}
}
}catch(Exception e){
}
return tables;
}
public Map<String,String> getColumns(String tablename){
Map<String,String> result = new HashMap<String, String>();
String sql = "desc "+tablename;
try{
pst = conn.prepareStatement(sql);
PreparedStatement pst = this.pst;
ResultSet res = pst.executeQuery();
while(res.next()){
String name = res.getString(1);
String type = res.getString(2);
result.put(name, type);
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public List<String> getPrimaryKey(String tableName){
List<String> list = new ArrayList<String>();
try{
DatabaseMetaData dmd = conn.getMetaData();
ResultSet result = dmd.getPrimaryKeys("", "", tableName);
while(result.next()){
list.add(result.getString(4));
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
public void close(){
try {
this.conn.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void setUrl(String url) {
this.url = url==null||"".equals(url)?DEFAULT_URL:url;
}
public void setName(String name) {
this.name = name==null||"".equals(name)?DEFAULT_NAME:name;
}
public void setUser(String user) {
this.user = user==null||"".equals(user)?DEFAULT_USER:user;
}
public void setPass(String pass) {
this.pass = pass==null||"".equals(pass)?DEFAULT_PASS:pass;
}
}
配置文件 vgenerator.properties
targetPackage=cc.vvxtoys.pojo
targetProject=src/main/java
objectName=Record
tableName=record
targetMapper=cc.vvxtoys.mapper
targetXML=cc.vvxtoys.mapper
user=root
url=jdbc\:mysql\://127.0.0.1\:3306/test?useUnicode\=true&characterEncoding\=utf8
name=com.mysql.jdbc.Driver
pass=root
基本的流程
- 初始化配置
- 初始化db
- 读取对应表的列
- 把列单位转换为java单位
- 开始构建
转换单位
/**
*author vvxtoys
*这个类是我用一个笨方法得到的,创建了一个所有类型的表,然后用mybatis-generator构建出来
*/
package cc.vvxtoys.bean;
public enum DBtype {
Date(",date,datetime,timestamp,year,time,"),
String(",longtext,text,varchar,enum,char,mediumtext,tinytext,set,"),
Double(",double,"),
Integer(",int,mediumint,"),
Short(",smallint,"),
Byte(",tinyint,"),
ByteArray(",tinyblob,mediumblob,binary,blob,longblob,varbinary,geometry,"),
Object(",point,multipoint,multilinestring,multipolygon,polygon,geometrycollection,linestring,"),
Long(",bigint,decimal,"),
Boolean(",bit,"),
Float(",float,");
private final String type;
private DBtype(String type) {
this.type = type;
}
public String getType() {
return type;
}
public static String getModelType(String dbtype){
if(dbtype.indexOf("(")!=-1){
dbtype = dbtype.substring(0,dbtype.indexOf("("));
}
dbtype = ","+dbtype+",";
for(DBtype db:DBtype.values()){
if(db.getType().indexOf(dbtype)!=-1){
String model = db.name();
if(model.equals("ByteArray")){
model = "byte[]";
}
return model;
}
}
return "String";
}
}
创建classFactory
/**
*@author vvxtoys
*该类实现拼接java
*生成属性、方法、构造,放进context
*/
package cc.vvxtoys.factory;
import java.util.ArrayList;
import java.util.List;
import cc.vvxtoys.bean.ClassBean;
import cc.vvxtoys.utils.Common;
import cc.vvxtoys.utils.Vconst;
import cc.vvxtoys.vgenerator.VgeneratorWrite;
public class ClassFactory {
private ClassBean bean;
public List<String> attrs;
public List<String> types;
public ClassFactory(ClassBean bean) {
this.bean = bean;
attrs = new ArrayList<String>();
types = new ArrayList<String>();
}
public void addAttribute(String declare,String type,String name){
StringBuffer buff = new StringBuffer();
buff.append(Vconst.TAB);
buff.append(declare);
buff.append(Vconst.SPACE);
buff.append(type);
buff.append(Vconst.SPACE);
buff.append(name);
buff.append(Vconst.END);
buff.append(Vconst.LINE);
bean.setAttributes(bean.getAttributes()+buff.toString());
attrs.add(name);
types.add(type);
}
public void addAttribute(String type,String name){
addAttribute("private", type, name);
}
public void addAttributes(String declare,String [] type,String [] name){
if(type.length!=name.length){
throw new IllegalArgumentException("Attribute not available");
}
for(int i=0;i<type.length;i++){
addAttribute(declare, type[i], name[i]);
}
}
public void addAttributes(String [] type,String [] name){
if(type.length!=name.length){
throw new IllegalArgumentException("Attribute not available");
}
for(int i=0;i<type.length;i++){
addAttribute(type[i], name[i]);
}
}
public void addGetMethod(String type,String name){
StringBuffer buffer = new StringBuffer();
buffer.append(Vconst.TAB);
buffer.append("public").append(Vconst.SPACE);
buffer.append(type).append(Vconst.SPACE);
buffer.append("get");
buffer.append(Common.upInitials(name)).append(Vconst.SPACE);
buffer.append("(");
buffer.append(")").append(Vconst.SPACE);
buffer.append("{").append(Vconst.LINE).append(Vconst.TTAB);
buffer.append("return").append(Vconst.SPACE);
buffer.append(name);
buffer.append(Vconst.END);
buffer.append(Vconst.LINE).append(Vconst.TAB);
buffer.append("}").append(Vconst.LINE);
bean.setMethods(bean.getMethods()+buffer.toString());
}
public void addSetMethod(String type,String name){
StringBuffer buffer = new StringBuffer();
buffer.append(Vconst.TAB);
buffer.append("public").append(Vconst.SPACE);
buffer.append("void").append(Vconst.SPACE);
buffer.append("set");
buffer.append(Common.upInitials(name)).append(Vconst.SPACE);
buffer.append("(");
buffer.append(type).append(Vconst.SPACE);
buffer.append(name);
buffer.append(")").append(Vconst.SPACE);
buffer.append("{").append(Vconst.LINE).append(Vconst.TTAB);
buffer.append("this.").append(name).append(Vconst.SPACE);
buffer.append("=").append(Vconst.SPACE).append(name);
buffer.append(Vconst.END);
buffer.append(Vconst.LINE).append(Vconst.TAB);
buffer.append("}").append(Vconst.LINE);
bean.setMethods(bean.getMethods()+buffer.toString());
}
public void addMethod(String type,String name){
addGetMethod(type, name);
addSetMethod(type, name);
}
public void autoAddMethod(){
for(int i=0;i<attrs.size();i++){
addMethod(types.get(i),attrs.get(i));
}
}
public void addConstructor(){
StringBuffer buffer = new StringBuffer();
buffer.append(Vconst.TAB);
buffer.append("public").append(Vconst.SPACE);
buffer.append(bean.getClazz()).append(Vconst.SPACE);
buffer.append("()").append(Vconst.SPACE);
buffer.append("{").append(Vconst.LINE).append(Vconst.TTAB);
buffer.append("super();").append(Vconst.LINE).append(Vconst.TAB);
buffer.append("}").append(Vconst.LINE);
buffer.append(Vconst.TAB);
buffer.append("public").append(Vconst.SPACE);
buffer.append(bean.getClazz()).append(Vconst.SPACE);
buffer.append("(");
for(int i=0;i<attrs.size();i++){
if(i>0){
buffer.append(",");
}
buffer.append(types.get(i)).append(Vconst.SPACE).append(attrs.get(i));
}
buffer.append(")").append(Vconst.SPACE);
buffer.append("{").append(Vconst.LINE).append(Vconst.TTAB);
buffer.append("super();").append(Vconst.LINE);
for(int j=0;j<attrs.size();j++){
buffer.append(Vconst.TTAB);
buffer.append("this.").append(attrs.get(j));
buffer.append(Vconst.SPACE).append("=").append(Vconst.SPACE);
buffer.append(attrs.get(j)).append(Vconst.END).append(Vconst.LINE);
}
buffer.append(Vconst.TAB);
buffer.append("}").append(Vconst.LINE);
bean.setConstructors(bean.getConstructors()+buffer.toString());
}
public void loadClass(String declare){
StringBuffer buff = new StringBuffer();
buff.append("package").append(Vconst.SPACE);
buff.append(bean.getPackages()).append(Vconst.END);
buff.append(Vconst.LINE).append(Vconst.LINE);
if(bean.isDependency()){
buff.append("import").append(Vconst.SPACE);
buff.append("java.util.Date").append(Vconst.END);
buff.append(Vconst.LINE).append(Vconst.LINE);
}
buff.append(declare).append(Vconst.SPACE);
buff.append("class").append(Vconst.SPACE);
buff.append(bean.getClazz()).append(Vconst.SPACE);
buff.append("{").append(Vconst.LINE).append(Vconst.LINE);
buff.append(bean.getAttributes());
buff.append(Vconst.LINE).append(Vconst.LINE);
buff.append(bean.getConstructors());
buff.append(Vconst.LINE).append(Vconst.LINE);
buff.append(bean.getMethods());
buff.append(Vconst.LINE).append(Vconst.LINE);
buff.append("}");
bean.setContext(buff.toString());
VgeneratorWrite.clazzs.add(bean);
}
public void loadClass(){
loadClass("public");
}
}
生成Mapper
/**
*@author vvxtoys
*根据主键来生成相对的方法
*没有主键只会生成insert方法
*/
package cc.vvxtoys.factory;
import java.util.ArrayList;
import java.util.List;
import cc.vvxtoys.bean.MapperBean;
import cc.vvxtoys.utils.Vconst;
import cc.vvxtoys.vgenerator.VgeneratorWrite;
public class MapperFactory {
private MapperBean bean;
public static List<String> knames;//主键
public static List<String> ktypes;//主键类型
public MapperFactory(MapperBean bean) {
this.bean = bean;
knames = new ArrayList<String>();
ktypes = new ArrayList<String>();
}
private String addKeyMethod(String method,String type) {
StringBuffer buffer = new StringBuffer();
buffer.append(Vconst.TAB);
buffer.append(type).append(Vconst.SPACE);
buffer.append(method).append("(");
for (int i = 0; i < knames.size(); i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(ktypes.get(i)).append(Vconst.SPACE).append(knames.get(i));
}
buffer.append(")").append(Vconst.END).append(Vconst.SPLIT);
return buffer.toString();
}
private String addMethod(String method) {
StringBuffer buffer = new StringBuffer();
buffer.append(Vconst.TAB);
buffer.append("int").append(Vconst.SPACE);
buffer.append(method).append("(");
buffer.append(bean.getClazz()).append(Vconst.SPACE).append("record");
buffer.append(")").append(Vconst.END).append(Vconst.SPLIT);
return buffer.toString();
}
private String addInsertMethod() {
return addMethod("insert");
}
private String addInsertSelectiveMethod() {
return addMethod("insertSelective");
}
private String addUpdateMethod() {
return addMethod("updateByPrimaryKeySelective");
}
private String addUpdateSelectiveMethod() {
return addMethod("updateByPrimaryKey");
}
public String addSelectMethod() {
return addKeyMethod("selectByPrimaryKey",bean.getClazz());
}
private String addDeleteMethod() {
return addKeyMethod("deleteByPrimaryKey","int");
}
public void loadMapper() {
StringBuffer buff = new StringBuffer();
buff.append("package").append(Vconst.SPACE);
buff.append(bean.getPackages()).append(Vconst.END);
buff.append(Vconst.SPLIT);
buff.append("import").append(Vconst.SPACE);
buff.append(bean.getPojo()).append(Vconst.END);
buff.append(Vconst.SPLIT);
buff.append("public").append(Vconst.SPACE);
buff.append("interface").append(Vconst.SPACE);
buff.append(bean.getClazz()).append("Mapper").append(Vconst.SPACE);
buff.append("{").append(Vconst.LINE);
if (bean.isPrimary()) {
buff.append(addDeleteMethod());
buff.append(addUpdateMethod());
buff.append(addUpdateSelectiveMethod());
buff.append(addSelectMethod());
}
buff.append(addInsertMethod());
buff.append(addInsertSelectiveMethod());
buff.append("}");
bean.setContext(buff.toString());
VgeneratorWrite.mappers.add(bean);//保存到写入类
}
}
xml工厂类
/**
*@author vvxtoys
*
*/
package cc.vvxtoys.factory;
import cc.vvxtoys.bean.XMLBean;
import cc.vvxtoys.utils.Vconst;
import cc.vvxtoys.vgenerator.SqlGenerator;
import cc.vvxtoys.vgenerator.VgeneratorWrite;
public class XMLFactory {
private double version = 1.0;
private String encoding = "UTF-8";
private boolean headDeclare = true;
//xml声明
private String docStart(){
StringBuffer buff = new StringBuffer();
buff.append("<?xml version=\"");
buff.append(version);
buff.append("\" encoding=\""+encoding+"\"");
buff.append(" ?>").append(Vconst.LINE);
return buff.toString();
}
public String addDoctype(String name, String publicId, String systemId){
Vconst.ROOTELEMENT[0] = name;//设置根节点
publicId = "\""+publicId+"\"";
systemId = "\""+systemId+"\"";
StringBuffer buffer = new StringBuffer(headDeclare?docStart():"");
buffer.append("<!DOCTYPE").append(Vconst.SPACE);
buffer.append(name).append(Vconst.SPACE);
buffer.append("PUBLIC ").append(publicId).append(Vconst.SPACE);
buffer.append(systemId).append(" >");
buffer.append(Vconst.LINE);
return buffer.toString();
}
public void createDoc(XMLBean bean,int k_size,int c_size){
bean.init();
String doctype = addDoctype(Vconst.DEFAULT_XML_ROOT, Vconst.DEFAULT_XML_PUBLICID, Vconst.DEFAULT_XML_SYSTEMID);
bean.addAttribute("namespace", bean.getMapper());
bean.setContext(doctype+bean.getContext());
SqlGenerator sql = new SqlGenerator(bean);//生成sql
sql.setK_size(k_size);
sql.setC_size(c_size);
sql.generatorSql();
VgeneratorWrite.xmls.add(bean);//保存xml文本
}
public void setVersion(Double version) {
this.version = version;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public void setHeadDeclare(boolean headDeclare) {
this.headDeclare = headDeclare;
}
}
逆向工程vgenerator(二)的更多相关文章
- 逆向工程vgenerator(三)
前言 该项目的最后一篇博文,最终构建,写入文件,整体项目流程将在本片文章中写出. jdbcType /** *@author vvxtoys *mysql单位 -> jdbcType */ pa ...
- 逆向工程vgenerator(一)
前言 想要自己实现一个mybatis-generator类似的轮子,目前只实现MySQL部分的方法.利用下班时间,写了一个小项目,实现了这个功能.我准备分成三篇博客来写这个东西. 基类 /** *基类 ...
- 小程序开发之后台mybatis逆向工程(二)
上一节搭建好了SSM后台框架,这一节将根据表结构创建实体及映射文件以及mapper接口.如果表过多,会很麻烦,所以mybatis提供了逆向工程来解决这个问题. 上一节 SSM搭建后台管理系统 逆向工程 ...
- MyBatis逆向工程的使用(非插件方式)
一.概述 MyBatis是目前流行的优秀持久层框架,其逆向工程更是大大缩减了开发时间.所谓逆向工程,指的是mybatis根据数据库设计好的表,自动生成对应model.mapper及mapper.xml ...
- Android混淆打包
一.理论知识 ProGuard是一款免费的Java类文件压缩器.优化器和混淆器.它能发现并删除无用类.字段(field).方法和属性值(attribute).它也能优化字节码并删除无用的指令.最后 ...
- ssm之mapper异常 Result Maps collection already contains value for com.ssj.mapper.UserMapper 和 Type interface com.ssj.mapper.UserMapper is already known to the MapperRegistry.
异常一:Result Maps collection already contains value for com.ssj.mapper.XXXMapper 原因分析:XXXmapper.xml文件中 ...
- PowerDesigner建模应用(二)逆向工程,导出PDM文件前过滤元数据(表、视图、存储过程等)
在上一篇文章<PowerDesigner建模应用(一)逆向工程,配置数据源并导出PDM文件>步骤二中导出了目标数据库对应的PDM文件, 该文件中展示出了所有表的信息与关系. 某些业务场景下 ...
- SpringBoot+Mybatis+Generator 逆向工程使用(二)
Mybatis-Genarator 逆向工程使用 个人开发环境 java环境:Jdk1.8.0_60 编译器:IntelliJ IDEA 2017.1.4 mysql驱动:mysql-connecto ...
- mybatis学习(十二)——mybatis逆向工程
MyBatis Generator (MBG)是一个mabatis的代码生成器,能够根据表自动生成mapper接口,mapper.xml文件,javaBean文件. 1.MBG的下载 打开https: ...
随机推荐
- java GMT时间转换为CST时间
今天在获取windchill的“上次修改时间”的时候发现获取的是GMT时间,但是我们常用的是CST时间 一开始尝试直接设置为CST时区,TimeZone.getTimeZone("CST&q ...
- 前端-----js
一 补充css的层叠性 权重: 行内样式(1000)>内接样式(如link等...) id(100)>class(010)>标签(001) 如果同是继承来的,距目标越近的优先级越高 ...
- @EnableScheduling注解
@EnableScheduling 开启对定时任务的支持 其中Scheduled注解中有以下几个参数: 1.cron是设置定时执行的表达式,如 0 0/5 * * * ?每隔五分钟执行一次 ...
- IDEA中的version control问题
项目已经添加了svn,但右键项目时找不到Svn选择.但在VCS中却有,很奇怪. 这个问题是svn的根路径与当前IDEA打开的项目路径不一致的原因. 在IdeaProjects下有两个项目,一个inju ...
- [R] [Johns Hopkins] R Programming 作業 Week 2 - Air Pollution
Introduction For this first programming assignment you will write three functions that are meant to ...
- java web(二): servlet的简单使用和介绍
前言:通过编写一个servlet类,向浏览器发送hello world来阐述servlet. 一:创建动态web项目 1. 首先切换到javaEE视图. 在ecplise左边即项目管理器哪里右键点击新 ...
- C++ 状态机接口
最近的状态极差,甚至代码也写不下去了.给自己手臂上的两刀没有任何的作用,看来早已经是麻痹了. 一直想弄一个勉强能用的状态机,用于在各种涉及到状态转换的时候用到,然而脑子并不是太清醒. 先放在这里一个接 ...
- jmeter的简单http接口用法
1. jmeter的启动:windows下的环境 进入jmeter的并目录双击启动 Mac电脑 进入bin目录找到jmeter.sh 文件 在终端执行./jmeter.sh 或者./jmeter. ...
- haproxy反向代理
haproxy是个高性能的tcp和http的反向代理.它就是个代理.不像nginx还做web服务器 官网地址为www.haproxy.org nginx的优点和缺点 优点: 1.web服务器,应用比较 ...
- git代理配置
命令行模式下配置 git config --global https.proxy https://proxyuser:proxypassword@ip/域名:port git config --glo ...