标签:
entity文件
# coding=utf-8
import MySQLdb
import sys
dbhost=‘192.168.2.200‘
dbport=3306
dbuser=‘root‘
dbpassword=‘zufangbao69fc‘
dbname=‘OrderCenter‘
dbtypes = {‘int‘:‘Integer‘, ‘bigint‘:‘Long‘, ‘bit‘:‘Boolean‘, ‘datetime‘:‘Date‘, ‘decimal‘:‘BigDecimal‘, ‘varchar‘:‘String‘,‘text‘:‘String‘}
defvalues = {‘int‘:‘0‘, ‘bigint‘:‘0L‘, ‘bit‘:‘false‘, ‘datetime‘:‘new Date()‘, ‘decimal‘:‘BigDecimal.ZERO‘, ‘varchar‘:‘StringUtils.EMPTY‘, ‘text‘:‘StringUtils.EMPTY‘}
def genEntity():
if len(sys.argv)<2:
print ‘pls input tablename,eg: python mybatisentity.py T_User‘
return
publicStr = ‘\r\n‘
tablename=sys.argv[1]
try:
conn=MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpassword,port=dbport,charset="utf8")
cur=conn.cursor()
conn.select_db(dbname)
print ‘import java.io.Serializable;‘
print ‘import java.math.BigDecimal;‘
print ‘import java.util.Date;‘
print ‘import org.apache.commons.lang3.StringUtils;‘
print ‘import com.fasterxml.jackson.databind.annotation.JsonDeserialize;‘
print ‘import com.fasterxml.jackson.databind.annotation.JsonSerialize;‘
print ‘import com.u51.utils.jackson.JacksonDateDeserializer;‘
print ‘import com.u51.utils.jackson.JacksonDateTimeSerializer;‘
count=cur.execute("select TABLE_COMMENT from information_schema.TABLES where TABLE_SCHEMA=‘" + dbname + "‘ and TABLE_NAME=‘" + tablename + "‘")
results=cur.fetchall()
print ‘/**‘
print ‘ * %s‘ % tablename
print ‘ * %s‘ % results[0][0]
print ‘ */‘
count=cur.execute("select * from information_schema.COLUMNS where TABLE_SCHEMA=‘" + dbname + "‘ and TABLE_NAME=‘" + tablename + "‘")
results=cur.fetchall()
print ‘public class %s implements Serializable {‘ % getEntityName(tablename)
print ‘\t/** */‘
print ‘\tprivate static final long serialVersionUID = 5775744684088434080L;‘
initDefaultValue = ‘‘
for r in results:
print ‘\t/**‘
print ‘\t * %s‘ % (‘‘ if r[19] is None else r[19].replace(‘\r‘,‘‘).replace(‘\n‘,‘‘))
print ‘\t */‘
if r[7] == ‘datetime‘:
print ‘\t@JsonSerialize(using = JacksonDateTimeSerializer.class)\r\n\t@JsonDeserialize(using = JacksonDateDeserializer.class)‘
print ‘\tprivate %s %s;‘ % (getType(r[7]), getFieldName(r[3]))
if r[16] is None or r[16] != ‘PRI‘:
if len(initDefaultValue) > 0:
initDefaultValue = ‘%s\r\n‘ % initDefaultValue
initDefaultValue = ‘%s\t\tthis.%s = %s;‘ % (initDefaultValue, getFieldName(r[3]), getDefaultValue(r[7], r[5] ))
publicStr = ‘%s\r\n\t/**\r\n\t * get <tt>%s</tt> %s\r\n\t */\r\n\tpublic %s get%s(){\r\n\t\treturn %s;\r\n\t}\r\n\r\n\t/**\r\n\t * set <tt>%s</tt> %s\r\n\t */\r\n\tpublic void set%s(%s %s){\r\n\t\tthis.%s = %s;\r\n\t}\r\n‘ % (publicStr,getFieldName(r[3]), ‘‘ if r[19] is None else r[19].replace(‘\r‘,‘‘).replace(‘\n‘,‘‘), getType(r[7]), getPublicFieldName(r[3]), getFieldName(r[3]), getFieldName(r[3]), ‘‘ if r[19] is None else r[19].replace(‘\r‘,‘‘).replace(‘\n‘,‘‘), getPublicFieldName(r[3]), getType(r[7]), getFieldName(r[3]), getFieldName(r[3]), getFieldName(r[3]))
print ‘\r\n\t/**‘
print ‘\t * 使用默认值初始化数据, 注意:在用于插入数据记录时,主键不能付值‘
print ‘\t */‘
print ‘\tpublic void initWithDefaultValue() {‘
print initDefaultValue
print ‘\t}‘
publicStr = publicStr[0: len(publicStr) - 2]
print publicStr
print ‘}‘
cur.close()
conn.close()
except MySQLdb.Error, e:
print "Mysql error %s: %s" %(e.args[0], e.args[0])
def getEntityName(tablename):
entityName=tablename
if tablename.startswith(‘T_‘):
entityName = tablename[2:]
entityName = entityName.replace(‘_‘,‘‘)
return ‘%sEntity‘ % entityName
def getType(type):
return dbtypes[type]
def getFieldName(field):
return "%s%s" % (field[0].lower(),field[1:])
def getPublicFieldName(field):
return ‘%s%s‘ % (field[0].upper(), field[1:])
def getDefaultValue(type, defval):
if type == ‘int‘ and defval is not None and len(defval)>0:
return defval
else:
return defvalues[type]
genEntity()
mapper文件
# coding=utf-8
import MySQLdb
import sys
dbhost=‘192.168.2.200‘
dbport=3306
dbuser=‘root‘
dbpassword=‘zufangbao69fc‘
dbname=‘OrderCenter‘
defaultEntityPackage = ‘com.u51.ordercenter.dao.entities‘
dbtypes = {‘int‘:‘Integer‘, ‘bigint‘:‘Long‘, ‘bit‘:‘Boolean‘, ‘datetime‘:‘Date‘, ‘decimal‘:‘BigDecimal‘, ‘varchar‘:‘String‘,‘text‘:‘String‘}
defvalues = {‘int‘:‘0‘, ‘bigint‘:‘0L‘, ‘bit‘:‘false‘, ‘datetime‘:‘new Date()‘, ‘decimal‘:‘BigDecimal.ZERO‘, ‘varchar‘:‘StringUtils.EMPTY‘, ‘text‘:‘StringUtils.EMPTY‘}
def genEntity():
if len(sys.argv)<2:
print ‘pls input tablename,eg: python mybatisentity.py T_User‘
return
publicStr = ‘\r\n‘
tablename=sys.argv[1]
if len(sys.argv)>2:
entityPackage = sys.argv[2]
else:
entityPackage = defaultEntityPackage
try:
conn=MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpassword,port=dbport,charset="utf8")
cur=conn.cursor()
conn.select_db(dbname)
print ‘import java.util.List;‘
print ‘import org.apache.ibatis.annotations.Param;‘
print ‘import %s.%s;‘ % (entityPackage, getEntityName(tablename))
count=cur.execute("select TABLE_COMMENT from information_schema.TABLES where TABLE_SCHEMA=‘" + dbname + "‘ and TABLE_NAME=‘" + tablename + "‘")
results=cur.fetchall()
print ‘/**‘
print ‘ * %s的DAO接口‘ % tablename
print ‘ * %s‘ % results[0][0]
print ‘ */‘
count=cur.execute("select COLUMN_NAME,DATA_TYPE from information_schema.COLUMNS where TABLE_SCHEMA=‘" + dbname + "‘ and TABLE_NAME=‘" + tablename + "‘ and COLUMN_KEY=‘PRI‘")
results=cur.fetchall()
pkName = results[0][0]
pkType = results[0][1]
print ‘public interface %s {‘ % getInterfaceName(tablename)
print ‘\t/**\r\n\t * 根据主键获取指定记录\r\n\t * @return 获取到的实体对象,如果没有找到则返回null\r\n\t */‘
print ‘\t%s findBy%s(@Param("%s") %s %s);‘ % (getEntityName(tablename), getPublicFieldName(pkName), getFieldName(pkName), getType(pkType), getFieldName(pkName))
print ‘\r\n\t/**\r\n\t * 保存记录\r\n\t * @return 获取主键,如果在保存的实体中已经指定主键,则返回null\r\n\t */‘
print ‘\t%s insert(@Param("record") %s record);‘ % (getType(pkType), getEntityName(tablename))
print ‘\r\n\t/**\r\n\t * 根据主键记录\r\n\t * @return 返回更新到的记录数\r\n\t */‘
print ‘\tint updateByPrimaryKey(@Param("record") %s record);‘ % (getEntityName(tablename))
print ‘\r\n\t/**\r\n\t * 根据示例查找符合条件的所有行\r\n\t * @return 返回查到的记录数\r\n\t */‘
print ‘\tint countByExample(@Param("example") %s example);‘ % (getEntityName(tablename))
print ‘\r\n\t/**\r\n\t * 根据示例查找符合条件的所有行\r\n\t * @return 返回查到的记录集合\r\n\t */‘
print ‘\tList<%s> findByExample(@Param("example") %s example);‘ % (getEntityName(tablename), getEntityName(tablename))
print ‘}‘
cur.close()
conn.close()
except MySQLdb.Error, e:
print "Mysql error %s: %s" %(e.args[0], e.args[0])
def getEntityName(tablename):
entityName=tablename
if tablename.startswith(‘T_‘):
entityName = tablename[2:]
entityName = entityName.replace(‘_‘,‘‘)
return ‘%sEntity‘ % entityName
def getInterfaceName(tablename):
interfaceName = tablename
if tablename.startswith(‘T_‘):
entityName = tablename[2:]
entityName = entityName.replace(‘_‘,‘‘)
return ‘%sMapper‘ % entityName
def getType(type):
return dbtypes[type]
def getFieldName(field):
return "%s%s" % (field[0].lower(),field[1:])
def getPublicFieldName(field):
return ‘%s%s‘ % (field[0].upper(), field[1:])
def getDefaultValue(type, defval):
if type == ‘int‘ and defval is not None and len(defval)>0:
return defval
else:
return defvalues[type]
genEntity()
xml文件
# coding=utf-8
import MySQLdb
import sys
dbhost=‘192.168.2.200‘
dbport=3306
dbuser=‘root‘
dbpassword=‘zufangbao69fc‘
dbname=‘OrderCenter‘
defaultEntityPackage = ‘com.u51.ordercenter.dao.entities‘
defaultMapperPackage = ‘com.u51.ordercenter.dao.mapper‘
idtypes = {‘int‘:‘java.lang.Integer‘, ‘bigint‘:‘java.lang.Long‘}
dbtypes = {‘int‘:‘INTEGER‘, ‘bigint‘:‘BIGINT‘, ‘bit‘:‘BIT‘, ‘datetime‘:‘TIMESTAMP‘, ‘decimal‘:‘DECIMAL‘, ‘varchar‘:‘VARCHAR‘,‘text‘:‘TEXT‘}
defvalues = {‘int‘:‘0‘, ‘bigint‘:‘0L‘, ‘bit‘:‘false‘, ‘datetime‘:‘new Date()‘, ‘decimal‘:‘BigDecimal.ZERO‘, ‘varchar‘:‘StringUtils.EMPTY‘, ‘text‘:‘StringUtils.EMPTY‘}
def genEntity():
if len(sys.argv)<2:
print ‘pls input tablename,eg: python mybatisentity.py T_User‘
return
tablename=sys.argv[1]
if len(sys.argv)>2:
entityPackage = sys.argv[2]
else:
entityPackage = defaultEntityPackage
if len(sys.argv)>3:
mapperPackage = sys.argv[3]
else:
mapperPackage = defaultMapperPackage
try:
conn=MySQLdb.connect(host=dbhost,user=dbuser,passwd=dbpassword,port=dbport,charset="utf8")
cur=conn.cursor()
conn.select_db(dbname)
print ‘<?xml version="1.0" encoding="UTF-8" ?>\r\n<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >\r\n<mapper namespace="%s.%s">\r\n\t<resultMap id="BaseResultMap" type="%s.%s">‘ % (mapperPackage, getInterfaceName(tablename), entityPackage, getEntityName(tablename))
count=cur.execute("select COLUMN_NAME,DATA_TYPE,COLUMN_KEY from information_schema.COLUMNS where TABLE_SCHEMA=‘" + dbname + "‘ and TABLE_NAME=‘" + tablename + "‘")
results=cur.fetchall()
fieldNames = ‘‘
pkName = ‘‘
pkType = ‘‘
insertFieldNames = ‘‘
insertFieldValues = ‘‘
updateFieldValues = ‘‘
whereFieldValues = ‘‘
for r in results:
if len(fieldNames)>0:
fieldNames = fieldNames + ‘,‘
fieldNames = ‘%s%s‘ % (fieldNames, r[0])
if r[2] is not None and r[2] == ‘PRI‘:
pkName = r[0]
pkType = r[1]
print ‘\t\t<id column="%s" property="%s" jdbcType="%s" />‘ % (r[0], getFieldName(r[0]), getType(r[1]))
else:
print ‘\t\t<result column="%s" property="%s" jdbcType="%s" />‘ % (r[0], getFieldName(r[0]), getType(r[1]))
if len(insertFieldNames) > 0:
insertFieldNames = insertFieldNames + ‘\r\n‘
insertFieldNames = ‘%s\t\t\t<if test="record.%s != null">\r\n\t\t\t\t%s,\r\n\t\t\t</if>‘ % (insertFieldNames, getFieldName(r[0]), r[0])
if len(insertFieldValues) > 0:
insertFieldValues = insertFieldValues + ‘\r\n‘
insertFieldValues = ‘%s\t\t\t<if test="record.%s != null">\r\n\t\t\t\t#{record.%s,jdbcType=%s},\r\n\t\t\t</if>‘ % (insertFieldValues, getFieldName(r[0]), getFieldName(r[0]), getType(r[1]))
if len(updateFieldValues)>0:
updateFieldValues = updateFieldValues + ‘\r\n‘
updateFieldValues = ‘%s\t\t\t<if test="record.%s != null">\r\n\t\t\t\t%s = #{record.%s,jdbcType=%s},\r\n\t\t\t</if>‘ % (updateFieldValues, getFieldName(r[0]), r[0], getFieldName(r[0]), getType(r[1]))
if len(whereFieldValues)>0:
whereFieldValues = whereFieldValues + ‘\r\n‘
whereFieldValues = ‘%s\t\t\t<if test="example.%s != null">\r\n\t\t\t\t%s = #{example.%s,jdbcType=%s} and\r\n\t\t\t</if>‘ % (whereFieldValues, getFieldName(r[0]), r[0], getFieldName(r[0]), getType(r[1]))
print ‘\t</resultMap>‘
print ‘\t<sql id="Base_Column_List">‘
print ‘\t\t%s‘ % fieldNames
print ‘\t</sql>‘
print ‘\t<select id="selectBy%s" resultMap="BaseResultMap" parameterType="java.util.HashMap">‘ % (getPublicFieldName(pkName), )
print ‘\t\tselect‘
print ‘\t\t<include refid="Base_Column_List" />‘
print ‘\t\tfrom %s‘ % tablename
print ‘\t\twhere %s = #{%s,jdbcType=%s}‘ % (pkName, getFieldName(pkName), getIdType(pkType))
print ‘\t</select>‘
print ‘\t<insert id="insert" parameterType="java.util.HashMap">‘
print ‘\t\t<selectKey resultType="%s" order="AFTER" keyProperty="%s">\r\n\t\t\tSELECT LAST_INSERT_ID() AS %s\r\n\t\t</selectKey>‘ % (getIdType(pkType), getFieldName(pkName), getFieldName(pkName))
print ‘\t\tinsert into %s‘ % tablename
print ‘\t\t<trim prefix="(" suffix=")" suffixOverrides=",">‘
print insertFieldNames
print ‘\t\t</trim>‘
print ‘\t\t<trim prefix="values (" suffix=")" suffixOverrides=",">‘
print insertFieldValues
print ‘\t\t</trim>‘
print ‘\t</insert>‘
print ‘\t<update id="updateByPrimaryKey" parameterType="java.util.HashMap">‘
print ‘\t\tupdate %s‘ % tablename
print ‘\t\t<set>‘
print updateFieldValues
print ‘\t\t</set>‘
print ‘\t\twhere %s = #{record.%s,jdbcType=%s}‘ % (pkName, getFieldName(pkName), getType(pkType))
print ‘\t</update>‘
print ‘\t<sql id="example_Where_Clause">\r\n\t\t<trim prefix="where " suffixOverrides=" and">‘
print whereFieldValues
print ‘\t\t</trim>\r\n\t</sql>‘
print ‘\t<select id="countByExample" parameterType="java.util.HashMap" resultType="java.lang.Integer">‘
print ‘\t\tselect count(*) from %s‘ % (tablename)
print ‘\t\t<include refid="example_Where_Clause" />‘
print ‘\t</select>‘
print ‘\t<select id="selectListByExample" resultMap="BaseResultMap" parameterType="java.util.HashMap">‘
print ‘\t\tselect‘
print ‘\t\t<include refid="Base_Column_List" />‘
print ‘\t\tfrom %s‘ % tablename
print ‘\t\t<include refid="example_Where_Clause" />‘
print ‘\t</select>‘
print ‘</mapper>‘
cur.close()
conn.close()
except MySQLdb.Error, e:
print "Mysql error %s: %s" %(e.args[0], e.args[0])
def getEntityName(tablename):
entityName=tablename
if tablename.startswith(‘T_‘):
entityName = tablename[2:]
entityName = entityName.replace(‘_‘,‘‘)
return ‘%sEntity‘ % entityName
def getInterfaceName(tablename):
interfaceName = tablename
if tablename.startswith(‘T_‘):
entityName = tablename[2:]
entityName = entityName.replace(‘_‘,‘‘)
return ‘%sMapper‘ % entityName
def getType(type):
return dbtypes[type]
def getIdType(type):
return idtypes[type]
def getFieldName(field):
return "%s%s" % (field[0].lower(),field[1:])
def getPublicFieldName(field):
return ‘%s%s‘ % (field[0].upper(), field[1:])
def getDefaultValue(type, defval):
if type == ‘int‘ and defval is not None and len(defval)>0:
return defval
else:
return defvalues[type]
genEntity()
标签:
原文地址:http://www.cnblogs.com/byshome/p/4795846.html