设为首页 收藏本站
查看: 695|回复: 0

[经验分享] 生成mybatis中所需的javabean和基础配置信息

[复制链接]

尚未签到

发表于 2016-11-28 07:38:08 | 显示全部楼层 |阅读模式
   如果在项目中使用到了mybatis,那么就需要编写与数据库表对应的javabean对象,还有数据库表的数据列和javabean对象中字段的映射配置,以及一些通用的插入更新数据的配置,这些都可以通过工具自动生成。

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.cogcn.framework.util.CommonUtil;
/**
* 把数据库中的表转化为java对象
*
* @author tuozixuan
*
*/
public class TableToJavaTool
{
private static final String DRIVER_NAME_ORACLE = "oracle.jdbc.driver.OracleDriver";
// 数据库连接-用户名
private String user;
// 数据库连接-密码
private String password;
// 数据库连接-URL
private String dbUrl;
// 表名
private String tableName;
// 表类别名称
private String catalog;
private final List<String> primaryKeyList = new ArrayList<String>();
private List<Map<String, Object>> dataList = null;
public TableToJavaTool()
{
}
public TableToJavaTool(String user, String password, String dbUrl, String tableName)
{
this.user = user;
this.password = password;
this.dbUrl = dbUrl;
this.tableName = tableName;
}
public void process()
{
dataList = readData(getTableName());
createJavaBeanFile(getTableName());
createMybatisColumnConfig(getTableName());
}
/**
* 获取数据库连接
*
* @return Connection 数据库连接对象
*/
private Connection getConnection()
{
Connection conn = null;
try
{
Properties props = new Properties();
props.put("remarksReporting", "true");
props.put("user", getUser());
props.put("password", getPassword());
Class.forName(DRIVER_NAME_ORACLE);
conn = DriverManager.getConnection(getDbUrl(), props);
}
catch (Exception e)
{
e.printStackTrace();
}
return conn;
}
/**
* 获取数据库指定表的列信息
*
* @param tableName 表名
* @return List<Map<String, Object>> 列信息列表
*/
private List<Map<String, Object>> readData(String tableName)
{
Connection conn = getConnection();
List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
try
{
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getColumns(getCatalog(), null, tableName, null);
Map<String, Object> map = null;
while (rs.next())
{
map = new HashMap<String, Object>();
map.put("columnName", rs.getString("COLUMN_NAME"));
map.put("dataType", rs.getInt("DATA_TYPE"));
map.put("remarks", rs.getString("REMARKS"));
dataList.add(map);
}
ResultSet rs1 = dbmd.getPrimaryKeys(getCatalog(), null, tableName);
while (rs1.next())
{
primaryKeyList.add(rs1.getString("COLUMN_NAME"));
}
}
catch (SQLException e)
{
e.printStackTrace();
} finally {
CommonUtil.closeConnection(conn);
}
return dataList;
}
public void createJavaBeanFile(String tableName)
{
StringBuffer jbString = new StringBuffer();
jbString.append("public class ").append(tableName).append("\r\n");
jbString.append("{").append("\r\n");
if (dataList != null)
{
for (Map<String, Object> map : dataList)
{
String fieldName = getFieldName((String) map.get("columnName"));
String javaType = getJavaType((Integer) map.get("dataType"));
jbString.append("    // ").append(map.get("remarks")).append("\r\n");
jbString.append("    private ").append(javaType).append(" ").append(fieldName).append(";").append("\r\n");
jbString.append("\r\n");
}
for (Map<String, Object> map : dataList)
{
String fieldName = getFieldName((String) map.get("columnName"));
String javaType = getJavaType((Integer) map.get("dataType"));
jbString.append("    public ").append(javaType).append(" get").append(firstUpperCase(fieldName)).append("()").append("\r\n");
jbString.append("    {").append("\r\n");
jbString.append("        return ").append(fieldName).append(";").append("\r\n");
jbString.append("    }").append("\r\n");
jbString.append("\r\n");
jbString.append("    public void set").append(firstUpperCase(fieldName)).append("(").append(javaType).append(" ").append(fieldName)
.append(")").append("\r\n");
jbString.append("    {").append("\r\n");
jbString.append("        this.").append(fieldName).append(" = ").append(fieldName).append(";").append("\r\n");
jbString.append("    }").append("\r\n");
jbString.append("\r\n");
}
}
jbString.append("}");
System.out.println(jbString.toString());
}
/**
* 根据表名获取对应的JavaBean的名称<br/>
*
*
* @param tableName 表名
* @return String JavaBean
*/
public static String getJavaBeanName(String tableName)
{
return tableName;
}
/**
* 把以_分隔的列明转化为字段名
*
* @param columnName 列名
* @return String 字段名
*/
private static String getFieldName(String columnName)
{
if (columnName == null)
{
return "";
}
StringBuffer fieldNameBuffer = new StringBuffer();
boolean nextUpperCase = false;
columnName = columnName.toLowerCase();
for (int i = 0; i < columnName.length(); i++)
{
char c = columnName.charAt(i);
if (nextUpperCase)
{
fieldNameBuffer.append(columnName.substring(i, i + 1).toUpperCase());
}
else
{
fieldNameBuffer.append(c);
}
if (c == '_')
{
nextUpperCase = true;
}
else
{
nextUpperCase = false;
}
}
String fieldName = fieldNameBuffer.toString();
fieldName = fieldName.replaceAll("_", "");
return fieldName;
}
/**
* 字符串的第一个字母大写
*
* @param str 字符串
* @return String 处理后的字符串
*/
private static String firstUpperCase(String str)
{
if (str == null)
{
return "";
}
if (str.length() == 1)
{
str = str.toUpperCase();
}
else
{
str = str.substring(0, 1).toUpperCase() + str.substring(1);
}
return str;
}
/**
* 将数据库列类型转换为java数据类型
*
* @param dataType 列类型
* @return String java数据类型
*/
private static String getJavaType(int dataType)
{
String javaType = "";
if (dataType == Types.INTEGER)
{
javaType = "int";
}
else if (dataType == Types.BIGINT)
{
javaType = "long";
}
else if (dataType == Types.CHAR || dataType == Types.VARCHAR || dataType == Types.NVARCHAR || dataType == Types.CLOB)
{
javaType = "String";
}
else if (dataType == Types.TINYINT)
{
javaType = "short";
}
else if (dataType == Types.FLOAT)
{
javaType = "float";
}
else if (dataType == Types.NUMERIC || dataType == Types.DECIMAL || dataType == Types.DOUBLE)
{
javaType = "double";
}
else if (dataType == Types.DATE || dataType == Types.TIMESTAMP)
{
javaType = "Date";
}
return javaType;
}
public void createMybatisColumnConfig(String tableName)
{
StringBuffer buffer = new StringBuffer();
if (dataList != null)
{
buffer.append("<resultMap id=\"BaseResultMap\" type=\"").append(tableName).append("\"> ").append("\r\n");
for (Map<String, Object> map : dataList)
{
// <result column="CI_TYP" jdbcType="CHAR" property="ciTyp" />
String columnName = (String) map.get("columnName");
String fieldName = getFieldName(columnName);
String jdbcType = getMybatisJdbcType((Integer) map.get("dataType"));
if (primaryKeyList.contains(columnName))
{
buffer.append("    <id column=\"").append(columnName).append("\" ").append("jdbcType=\"").append(jdbcType)
.append("\" property=\"").append(fieldName).append("\" />").append("\r\n");
} else {
buffer.append("    <result column=\"").append(columnName).append("\" ").append("jdbcType=\"").append(jdbcType)
.append("\" property=\"").append(fieldName).append("\" />").append("\r\n");
}
}
buffer.append("</resultMap>").append("\r\n");
}
buffer.append("<sql id=\"BaseColumnList\">").append("\r\n");
int length = dataList.size();
int count = 0;
buffer.append("    ");
for (Map<String, Object> map : dataList)
{
count++;
buffer.append(map.get("columnName"));
if (count != length)
{
buffer.append(", ");
}
}
buffer.append("\r\n");
buffer.append("</sql>").append("\r\n");
// insert配置
buffer.append("<insert id=\"insert\" parameterType=\"\">").append("\r\n");
buffer.append("    insert into ").append(getTableName()).append("\r\n");
buffer.append("    <trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">").append("\r\n");
for (Map<String, Object> map : dataList)
{
String columnName = (String) map.get("columnName");
String fieldName = getFieldName(columnName);
buffer.append("        <if test=\"").append(fieldName).append(" != null\"> \r\n");
buffer.append("            ").append(columnName).append(",").append("\r\n");
buffer.append("        </if> \r\n");
}
buffer.append("    </trim>").append("\r\n");
buffer.append("    <trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\"> \r\n");
for (Map<String, Object> map : dataList)
{
String columnName = (String) map.get("columnName");
String fieldName = getFieldName(columnName);
String jdbcType = getMybatisJdbcType((Integer) map.get("dataType"));
buffer.append("        <if test=\"").append(fieldName).append(" != null\"> \r\n");
buffer.append("            #{").append(fieldName).append(",jdbcType=").append(jdbcType).append("}, \r\n");
buffer.append("        </if> \r\n");
}
buffer.append("    </trim>").append("\r\n");
// update配置
buffer.append("<update id=\"update\" parameterType=\"java.util.Map\"> \r\n");
buffer.append("    update ").append(getTableName()).append("\r\n");
buffer.append("    <set>").append("\r\n");
for (Map<String, Object> map : dataList)
{
String columnName = (String) map.get("columnName");
String fieldName = getFieldName(columnName);
String jdbcType = getMybatisJdbcType((Integer) map.get("dataType"));
buffer.append("        <if test=\"").append(fieldName).append(" != null\"> \r\n");
buffer.append("            ").append(columnName).append(" = ").append("#{").append(fieldName).append(",jdbcType=").append(jdbcType).append("}, \r\n");
buffer.append("        </if> \r\n");
}
buffer.append("    </set> \r\n");
buffer.append("    where ").append("\r\n");
//        for (String primaryKey : primaryKeyList)
//        {
//            buffer.append("        ").append(primaryKey).append(" = #{lnNo,jdbcType=CHAR}");
//        }
buffer.append("</update>");

System.out.println(buffer.toString());
}
/**
* 根据列的类型,获取mybatis配置中的jdbcType
*
* @param dataType 列的类型
* @return String jdbcType
*/
private static String getMybatisJdbcType(int dataType)
{
String jdbcType = "";
if (dataType == Types.TINYINT)
{
jdbcType = "TINYINT";
}
else if (dataType == Types.SMALLINT)
{
jdbcType = "SMALLINT";
}
else if (dataType == Types.INTEGER)
{
jdbcType = "INTEGER";
}
else if (dataType == Types.BIGINT)
{
jdbcType = "BIGINT";
}
else if (dataType == Types.FLOAT)
{
jdbcType = "FLOAT";
}
else if (dataType == Types.DOUBLE)
{
jdbcType = "DOUBLE";
}
else if (dataType == Types.DECIMAL)
{
jdbcType = "DECIMAL";
}
else if (dataType == Types.NUMERIC)
{
jdbcType = "NUMERIC";
}
else if (dataType == Types.VARCHAR)
{
jdbcType = "VARCHAR";
}
else if (dataType == Types.NVARCHAR)
{
jdbcType = "NVARCHAR";
}
else if (dataType == Types.CHAR)
{
jdbcType = "CHAR";
}
else if (dataType == Types.NCHAR)
{
jdbcType = "NCHAR";
}
else if (dataType == Types.CLOB)
{
jdbcType = "CLOB";
}
else if (dataType == Types.BLOB)
{
jdbcType = "BLOB";
}
else if (dataType == Types.NCLOB)
{
jdbcType = "NCLOB";
}
else if (dataType == Types.DATE)
{
jdbcType = "DATE";
}
else if (dataType == Types.TIMESTAMP)
{
jdbcType = "TIMESTAMP";
}
else if (dataType == Types.ARRAY)
{
jdbcType = "ARRAY";
}
else if (dataType == Types.TIME)
{
jdbcType = "TIME";
}
else if (dataType == Types.BOOLEAN)
{
jdbcType = "BOOLEAN";
}
else if (dataType == Types.BIT)
{
jdbcType = "BIT";
}
else if (dataType == Types.BINARY)
{
jdbcType = "BINARY";
}
else if (dataType == Types.OTHER)
{
jdbcType = "OTHER";
}
else if (dataType == Types.REAL)
{
jdbcType = "REAL";
}
else if (dataType == Types.LONGVARCHAR)
{
jdbcType = "LONGVARCHAR";
}
else if (dataType == Types.VARBINARY)
{
jdbcType = "VARBINARY";
}
else if (dataType == Types.LONGVARBINARY)
{
jdbcType = "LONGVARBINARY";
}
return jdbcType;
}
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getDbUrl()
{
return dbUrl;
}
public void setDbUrl(String dbUrl)
{
this.dbUrl = dbUrl;
}
public String getTableName()
{
return tableName;
}
public void setTableName(String tableName)
{
this.tableName = tableName;
}
public String getCatalog()
{
return catalog;
}
public void setCatalog(String catalog)
{
this.catalog = catalog;
}
}

  使用示例:

    public static void main(String[] args)
{
String dbUrl = "jdbc:oracle:thin:@10.10.16.80:1521/orcl";
String userName = "user";
String password = "password";
String tableName = "MEMBER";
TableToJavaTool tool = new TableToJavaTool(userName, password, dbUrl, tableName);
// tool.setCatalog("me");
tool.process();
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-306332-1-1.html 上篇帖子: spring,mybatis事务管理配置与 Transactional注解使用 下篇帖子: ibatis3 (mybatis) 实例代码下载兼ibatis3优劣分析
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表