/**
* 通过注解拼接建表语句 * create table test_person( * pid number(10) primary key, * person_name varchar2(255) * ); * 思路: * * */@Table(name="test_person")public class Person { @Id private Integer pid; @Column(name="person_name") private String pname; public Integer getPid() { return pid; } public void setPid(Integer pid) { this.pid = pid; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public static void main(String[] args) { Class clazz = Person.class; Table table = (Table)clazz.getAnnotation(Table.class); StringBuffer sql = new StringBuffer("create table "+table.name()+" ("); Field[] fields = clazz.getDeclaredFields(); for(int i = 0;i<fields.length;i++){ String fieldName = fields[i].getName(); Column col = fields[i].getAnnotation(Column.class); String colName = col==null?fieldName:col.name();//获取列名 sql.append(colName); if(fields[i].getType()==Integer.class){ sql.append(" number(10) "); }else if(fields[i].getType()==String.class){ sql.append(" varchar2(255) "); } Id id = fields[i].getAnnotation(Id.class); String pkContent = id==null?",":"primary key,"; sql.append(pkContent); } sql.deleteCharAt(sql.length()-1); sql.append(")"); System.out.println(sql); }}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)public @interface Table { public String name() default("");}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD})public @interface Id {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD})public @interface Column { public String name() default("");}