获取注解配置的hibernate的model对应字段名和表名

注意,引用的是javax.persistence.Column和javax.persistence.Table,起初我以为注解既然配置的是Hibernate的实体用的,是不是应该引用hibernate包下的table和column,后来出了问题,找了好长时间才发现问题出在应该引用的不是hibernate包里的,方法可以写main方法测试。
        import java.lang.annotation.Annotation;
        import java.lang.reflect.Field;
        import javax.persistence.Column;
        import javax.persistence.Table;
        /**
 * 获取字段
 * 
 * @param classtype
 */
@SuppressWarnings(value = { "rawtypes" })
public static Map<String, String> getColumns(Class classtype) {
Field[] fields = classtype.getDeclaredFields();
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < fields.length; i++) {
Annotation[] annotations = fields[i].getAnnotations();
for (int j = 0; j < annotations.length; j++) {
if (annotations[j] instanceof Column) {
Column column = (Column) annotations[j];
System.out.print(fields[i].getName() + "、");
System.out.println(column.name());
map.put(fields[i].getName(), column.name());
}
}
}
return map;
}

/**
 * 获取表名
 * 
 * @param classtype
 * @return
 */
@SuppressWarnings(value = { "rawtypes" })
public static String getTableName(Class classtype) {
Annotation[] anno = classtype.getAnnotations();
String tableName = "";
for (int i = 0; i < anno.length; i++) {
if (anno[i] instanceof Table) {
Table table = (Table) anno[i];
System.out.println(table.name());
tableName = table.name();
}
}
return tableName;
}
阅读更多

没有更多推荐了,返回首页