生成java实体的脚本
import MySQLdb import sys dbhost=‘192.168.2.200‘ dbport=3306 dbuser=‘root‘ dbpassword=‘zufangbao69fc‘ dbname=‘houseloan‘ dbtypes = {‘int‘:‘Integer‘, ‘bigint‘:‘Long‘, ‘bit‘:‘Boolean‘, ‘datetime‘:‘Date‘, ‘decimal‘:‘BigDecimal‘, ‘varchar‘:‘String‘} defvalues = {‘int‘:‘0‘, ‘bigint‘:‘0L‘, ‘bit‘:‘false‘, ‘datetime‘:‘new Date()‘, ‘decimal‘:‘BigDecimal.ZERO‘, ‘varchar‘:‘StringUtils.EMPTY‘} def genEntity(): if len(sys.argv)<2: print ‘pls input tablename,eg: python entity.py T_User‘ return 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) count=cur.execute("select * from information_schema.COLUMNS where TABLE_SCHEMA=‘" + dbname + "‘ and TABLE_NAME=‘" + tablename + "‘") results=cur.fetchall() publicStr = ‘\r\n‘ print ‘@Entity‘ print ‘@Table(name = "%s")‘ % tablename print ‘public class %s implements Serializable {‘ % getEntityName(tablename) for r in results: print ‘\t/**‘ print ‘\t * %s‘ % (‘‘ if r[19] is None else r[19].replace(‘\r‘,‘‘).replace(‘\n‘,‘‘)) print ‘\t */‘ print ‘\[email protected](name = "%s")‘ % r[3] if r[16] is not None and r[16] == ‘PRI‘: print ‘\[email protected]‘ if r[17] is not None and r[17]==‘auto_increment‘: print ‘\[email protected](strategy = GenerationType.AUTO)‘ print ‘\tprivate %s %s;‘ % (getType(r[7]), getFieldName(r[3])) else: print ‘\tprivate %s %s = %s;‘ % (getType(r[7]), 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 publicStr print ‘}‘ cur.close() conn.close() except MySQLdb.Error, e: print "Mysql error %d: %s" %(e.args[0], e.args[1]) 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()
时间: 2024-10-17 05:28:24