分享一份自己写的关于ssh框架自动生成Bean的源代码和思路
2017-07-27 21:36
531 查看
一开始是想mybatis有自动生成bean的工具,但hibernate却没有或者是我没接触到,就想利用反射机制实现由表到实体类自动生成的工具类,但其实这个方式行不通,java的反射机制虽然强大,但也没办法无中生有。于是在网上搜了下,发现已经有前辈写过这类工具类,使用的是io流,直接创建.java文件 具体的代码如下希望不足之处可以得到大家的提点
首先是处理字符串的工具类:
import java.io.PrintWriter;
import com.cxb.myexception.IllegalException;
/**
* 字符串处理
* @author MrChen
*
*/
public class StringUtil {
/**
* 将set方法写入流中
* @param writer 目标流
* @param columnName 数据库字段名
* @param type 数据类型 java类型
* @throws IllegalException
*/
public static void gainSetMethod(PrintWriter writer,String columnName,String type)throws IllegalException{
String beanName=StringUtil.gainBeanString(columnName);
char[] ch = beanName.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
writer.println("\tpublic void set"+new String(ch)+"("+type+" "+beanName+"){");
writer.println("\t\t this."+beanName+"="+beanName+";\n\t}");
}
/**
* 将get方法写入流中
* @param writer 目标流
* @param columnName 数据库字段名
* @param type 数据类型 java类型
* @throws IllegalException
*/
public static void gainGetMethod(PrintWriter writer,String columnName,String type)throws IllegalException{
String beanName=StringUtil.gainBeanString(columnName);
char[] ch = beanName.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
writer.println("\tpublic "+type+" get"+new String(ch)+"(){");
writer.println("\t\treturn this."+beanName+";\n\t}");
}
/**
* 根据_将表名转为首字母大写的ClassName
* @param tableName 表名 WORD_WORD or T_WORD_WORD
* @return
* @throws IllegalException
*/
public static String gainClassNameString(String tableName) throws IllegalException{
return StringUtil.gainBeanString(tableName, "_", 1);
}
/**
* 根据_将数据库字段转为驼峰法的Bean字段
* @param columnName 数据库字段 WORD_WORD or T_WORD_WORD
* @return
* @throws IllegalException
*/
public static String gainBeanString(String columnName)throws IllegalException{
return StringUtil.gainBeanString(columnName, "_", 0);
}
/**
* 根据正则表达式分离字段并拼接为驼峰法命名的Bean字段或首字母大写的className字段
* @param tableString
* @param regex
* @param type 0-BeanName !0-ClassName
* @return
* throws IllegalException
*/
public static String gainBeanString(String tableString,String regex,int type)throws IllegalException{
try{
if(tableString==null||"".equals(tableString)){
throw new IllegalException("字符不能为null");
}
String[] words=tableString.split(regex);//根据下划线讲字段分离
if(words.length<=0){
throw new IllegalException("非法数据库命名");
}
if(words.length==1){
if(type==0){
return words[0].toLowerCase();
}else{
return StringUtil.initialString(words[0]);
}
}
StringBuilder targetStr=new StringBuilder();
//拼接首个字段
int firstInt=0;
if(words[0].equalsIgnoreCase("T"))
firstInt=1;
if(type==0){
targetStr.append(words[firstInt].toLowerCase());
}else{
targetStr.append(StringUtil.initialString(words[firstInt]));
}
//拼接其余字段
for (int i = firstInt+1; i < words.length; i++) {
targetStr.append(StringUtil.initialString(words[i]));
}
return targetStr.toString();
}catch(IllegalException e){
e.printStackTrace();
throw new IllegalException("非法字符:"+tableString);
}
}
/**
* 返回一个首字母大写的字符串
* @param str
* @return
*/
public static String initialString(String str)throws IllegalException{
try{
str=str.toLowerCase();
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}catch(Exception e){
e.printStackTrace();
throw new IllegalException("字符首字母转换异常:"+str);
}
}
}
----------------------------------------------------------生成Bean工具类---------------------------------------------------
package com.cxb.util;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Date;
import javax.annotation.Resource;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* 根据数据库表自动生成Bean
* @author MrChen
*
*/
@Transactional
@Component(value="createBean")
public class CreateBean {
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
private String packagePath="\\src\\main\\java\\com\\cxb\\model";//生成的包路径
/**
* @param userName 数据库用户名
* @param packageStr 生成的Bean所在目录
* @return
*/<
4000
br />
public int createBean(String userName,String packageStr){
try{
String directory=System.getProperty("user.dir");
directory+="\\src\\main\\java\\"+packageStr;
directory=directory.toLowerCase();
System.out.println(directory);
//生成路径
new File(directory).mkdirs();
//获取所有表名
StringBuilder sql=new StringBuilder();
sql.append("select table_name from user_tables t");
if(userName!=null){
sql.append(" where t.TABLESPACE_NAME='");
sql.append(userName.toUpperCase());
sql.append("'");
}
System.out.println(sql);
//获取当前用户下的所有表名
List<String> tableName=getSession().createSQLQuery(sql.toString()).list();
int tableSize=0;
System.out.println("当期共获取表名:"+tableName.size());
for (String string : tableName) {
try{
//排除工作流表
if(string.toUpperCase().startsWith("ACT"))
continue;
List<Map<String, Object>> temp=findTableDesc(string);
//创建.java文件
String tempUrl=directory+"\\"+StringUtil.gainClassNameString(string)+".java";
File file=new File(tempUrl);
file.createNewFile();
PrintWriter write=new PrintWriter(file,"UTF-8");
//写入所属空间
write.println("package\t"+packageStr.toLowerCase().replaceAll("\\\\", ".")+";");
//导入包
write.println("import\tjavax.persistence.Column;");
write.println("import\tjavax.persistence.Entity;");
write.println("import\tjavax.persistence.GeneratedValue;");
write.println("import\tjavax.persistence.GenerationType;");
write.println("import\tjavax.persistence.Id;");
write.println("import\tjavax.persistence.SequenceGenerator;");
write.println("import\tjavax.persistence.Table;");
write.println("import\tjava.util.Date;");
//写入类及类主键
write.println("@Entity\n@Table(name=\""+string+"\")\npublic class "+StringUtil.gainClassNameString(string)+"{\n");
//写入主键
write.println("\tprivate Integer "+StringUtil.gainBeanString((String)temp.get(0).get("COLUMN_NAME"))+";");
//写入get&set方法
write.println("\t@Id");
if(temp.get(0).get("NULLABLE").equals("N")){
write.println("\t@SequenceGenerator(name=\"seq_generator\",sequenceName=\"table_id\", allocationSize = 1)");
write.println("\t@GeneratedValue(generator=\"seq_generator\",strategy=GenerationType.SEQUENCE)");
}
write.println("\t@Column(name=\""+temp.get(0).get("COLUMN_NAME")+"\")");
StringUtil.gainGetMethod(write, (String)temp.get(0).get("COLUMN_NAME"), "Integer");
StringUtil.gainSetMethod(write, (String)temp.get(0).get("COLUMN_NAME"), "Integer");
//写入其他字段
for (int i = 1; i < temp.size(); i++) {
//获取数据类型
String type="";
switch((String)temp.get(i).get("DATA_TYPE")){
case "NUMBER":
case "Integer":
type="Integer";
break;
case "NVARCHAR2":
case "VARCHAR2":
case "VARCHAR":
type="String";
break;
case "TIMESTAMP(6)":
case "TIMESTAMP(3)":
case "DATE":
type="Date";
break;
default:
type="String";
break;
}
write.println("\tprivate "+type+" "+StringUtil.gainBeanString((String)temp.get(i).get("COLUMN_NAME"))+";");
write.println("\t@Column(name=\""+temp.get(i).get("COLUMN_NAME")+"\")");
StringUtil.gainGetMethod(write, (String)temp.get(i).get("COLUMN_NAME"), type);
StringUtil.gainSetMethod(write, (String)temp.get(i).get("COLUMN_NAME"), type);
}
write.print("}");
write.flush();
}catch(Exception e){
System.err.println(string+"表创建Bean失败"+(++tableSize));
}
}
}catch(Exception e){
e.printStackTrace();
}
return 0;
}
/**
* 构建get/set方法
*/
public void createSetAndGet(PrintWriter writer,String FieldName){
}
/**
* 获取表结构
* @return
*/
public List<Map<String, Object>> findTableDesc(String tableName){
return getSession().createSQLQuery("select COLUMN_NAME,DATA_TYPE,NULLABLE from user_tab_columns where Table_Name='"+tableName+"'").setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
}
public Session getSession() {
return this.sessionFactory.getCurrentSession();
// .getCurrentSession();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
首先是处理字符串的工具类:
import java.io.PrintWriter;
import com.cxb.myexception.IllegalException;
/**
* 字符串处理
* @author MrChen
*
*/
public class StringUtil {
/**
* 将set方法写入流中
* @param writer 目标流
* @param columnName 数据库字段名
* @param type 数据类型 java类型
* @throws IllegalException
*/
public static void gainSetMethod(PrintWriter writer,String columnName,String type)throws IllegalException{
String beanName=StringUtil.gainBeanString(columnName);
char[] ch = beanName.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
writer.println("\tpublic void set"+new String(ch)+"("+type+" "+beanName+"){");
writer.println("\t\t this."+beanName+"="+beanName+";\n\t}");
}
/**
* 将get方法写入流中
* @param writer 目标流
* @param columnName 数据库字段名
* @param type 数据类型 java类型
* @throws IllegalException
*/
public static void gainGetMethod(PrintWriter writer,String columnName,String type)throws IllegalException{
String beanName=StringUtil.gainBeanString(columnName);
char[] ch = beanName.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
writer.println("\tpublic "+type+" get"+new String(ch)+"(){");
writer.println("\t\treturn this."+beanName+";\n\t}");
}
/**
* 根据_将表名转为首字母大写的ClassName
* @param tableName 表名 WORD_WORD or T_WORD_WORD
* @return
* @throws IllegalException
*/
public static String gainClassNameString(String tableName) throws IllegalException{
return StringUtil.gainBeanString(tableName, "_", 1);
}
/**
* 根据_将数据库字段转为驼峰法的Bean字段
* @param columnName 数据库字段 WORD_WORD or T_WORD_WORD
* @return
* @throws IllegalException
*/
public static String gainBeanString(String columnName)throws IllegalException{
return StringUtil.gainBeanString(columnName, "_", 0);
}
/**
* 根据正则表达式分离字段并拼接为驼峰法命名的Bean字段或首字母大写的className字段
* @param tableString
* @param regex
* @param type 0-BeanName !0-ClassName
* @return
* throws IllegalException
*/
public static String gainBeanString(String tableString,String regex,int type)throws IllegalException{
try{
if(tableString==null||"".equals(tableString)){
throw new IllegalException("字符不能为null");
}
String[] words=tableString.split(regex);//根据下划线讲字段分离
if(words.length<=0){
throw new IllegalException("非法数据库命名");
}
if(words.length==1){
if(type==0){
return words[0].toLowerCase();
}else{
return StringUtil.initialString(words[0]);
}
}
StringBuilder targetStr=new StringBuilder();
//拼接首个字段
int firstInt=0;
if(words[0].equalsIgnoreCase("T"))
firstInt=1;
if(type==0){
targetStr.append(words[firstInt].toLowerCase());
}else{
targetStr.append(StringUtil.initialString(words[firstInt]));
}
//拼接其余字段
for (int i = firstInt+1; i < words.length; i++) {
targetStr.append(StringUtil.initialString(words[i]));
}
return targetStr.toString();
}catch(IllegalException e){
e.printStackTrace();
throw new IllegalException("非法字符:"+tableString);
}
}
/**
* 返回一个首字母大写的字符串
* @param str
* @return
*/
public static String initialString(String str)throws IllegalException{
try{
str=str.toLowerCase();
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}catch(Exception e){
e.printStackTrace();
throw new IllegalException("字符首字母转换异常:"+str);
}
}
}
----------------------------------------------------------生成Bean工具类---------------------------------------------------
package com.cxb.util;
import java.io.File;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Date;
import javax.annotation.Resource;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* 根据数据库表自动生成Bean
* @author MrChen
*
*/
@Transactional
@Component(value="createBean")
public class CreateBean {
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
private String packagePath="\\src\\main\\java\\com\\cxb\\model";//生成的包路径
/**
* @param userName 数据库用户名
* @param packageStr 生成的Bean所在目录
* @return
*/<
4000
br />
public int createBean(String userName,String packageStr){
try{
String directory=System.getProperty("user.dir");
directory+="\\src\\main\\java\\"+packageStr;
directory=directory.toLowerCase();
System.out.println(directory);
//生成路径
new File(directory).mkdirs();
//获取所有表名
StringBuilder sql=new StringBuilder();
sql.append("select table_name from user_tables t");
if(userName!=null){
sql.append(" where t.TABLESPACE_NAME='");
sql.append(userName.toUpperCase());
sql.append("'");
}
System.out.println(sql);
//获取当前用户下的所有表名
List<String> tableName=getSession().createSQLQuery(sql.toString()).list();
int tableSize=0;
System.out.println("当期共获取表名:"+tableName.size());
for (String string : tableName) {
try{
//排除工作流表
if(string.toUpperCase().startsWith("ACT"))
continue;
List<Map<String, Object>> temp=findTableDesc(string);
//创建.java文件
String tempUrl=directory+"\\"+StringUtil.gainClassNameString(string)+".java";
File file=new File(tempUrl);
file.createNewFile();
PrintWriter write=new PrintWriter(file,"UTF-8");
//写入所属空间
write.println("package\t"+packageStr.toLowerCase().replaceAll("\\\\", ".")+";");
//导入包
write.println("import\tjavax.persistence.Column;");
write.println("import\tjavax.persistence.Entity;");
write.println("import\tjavax.persistence.GeneratedValue;");
write.println("import\tjavax.persistence.GenerationType;");
write.println("import\tjavax.persistence.Id;");
write.println("import\tjavax.persistence.SequenceGenerator;");
write.println("import\tjavax.persistence.Table;");
write.println("import\tjava.util.Date;");
//写入类及类主键
write.println("@Entity\n@Table(name=\""+string+"\")\npublic class "+StringUtil.gainClassNameString(string)+"{\n");
//写入主键
write.println("\tprivate Integer "+StringUtil.gainBeanString((String)temp.get(0).get("COLUMN_NAME"))+";");
//写入get&set方法
write.println("\t@Id");
if(temp.get(0).get("NULLABLE").equals("N")){
write.println("\t@SequenceGenerator(name=\"seq_generator\",sequenceName=\"table_id\", allocationSize = 1)");
write.println("\t@GeneratedValue(generator=\"seq_generator\",strategy=GenerationType.SEQUENCE)");
}
write.println("\t@Column(name=\""+temp.get(0).get("COLUMN_NAME")+"\")");
StringUtil.gainGetMethod(write, (String)temp.get(0).get("COLUMN_NAME"), "Integer");
StringUtil.gainSetMethod(write, (String)temp.get(0).get("COLUMN_NAME"), "Integer");
//写入其他字段
for (int i = 1; i < temp.size(); i++) {
//获取数据类型
String type="";
switch((String)temp.get(i).get("DATA_TYPE")){
case "NUMBER":
case "Integer":
type="Integer";
break;
case "NVARCHAR2":
case "VARCHAR2":
case "VARCHAR":
type="String";
break;
case "TIMESTAMP(6)":
case "TIMESTAMP(3)":
case "DATE":
type="Date";
break;
default:
type="String";
break;
}
write.println("\tprivate "+type+" "+StringUtil.gainBeanString((String)temp.get(i).get("COLUMN_NAME"))+";");
write.println("\t@Column(name=\""+temp.get(i).get("COLUMN_NAME")+"\")");
StringUtil.gainGetMethod(write, (String)temp.get(i).get("COLUMN_NAME"), type);
StringUtil.gainSetMethod(write, (String)temp.get(i).get("COLUMN_NAME"), type);
}
write.print("}");
write.flush();
}catch(Exception e){
System.err.println(string+"表创建Bean失败"+(++tableSize));
}
}
}catch(Exception e){
e.printStackTrace();
}
return 0;
}
/**
* 构建get/set方法
*/
public void createSetAndGet(PrintWriter writer,String FieldName){
}
/**
* 获取表结构
* @return
*/
public List<Map<String, Object>> findTableDesc(String tableName){
return getSession().createSQLQuery("select COLUMN_NAME,DATA_TYPE,NULLABLE from user_tab_columns where Table_Name='"+tableName+"'").setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
}
public Session getSession() {
return this.sessionFactory.getCurrentSession();
// .getCurrentSession();
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
相关文章推荐
- 自己最近做的一个关于自动进入飞行模式的经验分享
- .NET不用代码生成器自己写一个生成Code的DLL 自动动态生成三层架构(一)概况
- 产品和产品规格(产品变量)自动生成SKU的需求解决思路
- [MySQL-MM] 生产环境自动恢复MM中一台M2库的过程,分享从零开始写的自动化重建脚本以及思路 (转)
- 关于tinker自动生成application失败的问题
- Eclipse使用generator,自动生成Sql和Bean
- JAXB注解 java 关于xml的注解,自动生成xml文件 - @XML***
- 【原创】搭建SSH后通过反向工程(Reverse Engineering)自动生成Hibernate Bean实体和Spring Dao对象详解(图文)
- 关于Idea IDE可以自动生成java代理的生产过程栗子
- 关于Swift@IBOutlet连线生成的属性系统自动解包问题
- 写了一个能自定义并自动按照规则生成单据号码的程序及相关存储过程和表,及示范,附全部源代码!
- 关于Excel Vba 自动生成代码的一些研究
- 转帖 分享代码自动生成
- myeclipse自动生成javabean
- java mysql 表中字段是tinyint(1)类型,hibernate自动生成bean对应属性为boolean类型,如何传值
- vs技巧分享:多程序集解决方案里临时文件清除和生成目录里依赖的第3方类库外部文件自动生成
- 关于集成JPush过程中一些思考--仅供自己开阔思路
- 仿orm自动生成分页SQL分享
- TC脚本开发-梦幻诛仙自动登录思路梳理及源代码
- 关于SQL语句的自动生成!(一)