Spring 扫描实体包,获取实体对应的表名和字段

扫描@Table @Column @EmbeddedId 注解,获取实体的表名和字段名

List list = new ArrayList<>();
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Table.class));
        for (BeanDefinition bd : scanner.findCandidateComponents("com.test.domain.*")) {
            Class clazz = Class.forName(bd.getBeanClassName());
            Table myClassAnnotation = clazz.getAnnotation(Table.class);
            String tableNm = myClassAnnotation.name().toUpperCase();

            // 获得字段注解
            Field fields[] = clazz.getDeclaredFields();
            for (Field field : fields) {
            	// 获取普通属性的@Column注解
                Column myFieldAnnotation = field.getAnnotation(Column.class);
                if (myFieldAnnotation != null) {
                    String fieldNm = myFieldAnnotation.name().toUpperCase();
                    String[] obj = { tableNm, fieldNm };
                    list.add(obj);
                }
				// 获取联合主键的字段列名
                EmbeddedId embeddedAnno = field.getAnnotation(EmbeddedId.class);
                if(embeddedAnno != null) {
                    Class subClazz = field.getType();
                    Field subFileds[] = subClazz.getDeclaredFields();
                    for (Field subFiled : subFileds) {
                        Column myFieldSub = subFiled.getAnnotation(Column.class);
                        if (myFieldSub != null) {
                            String fieldNm = myFieldSub.name().toUpperCase();
                            String[] obj = {tableNm, fieldNm};
                            list.add(obj);
                        }
                    }
                }
            }
            // 获取方法上的@Column 注解
            Method methods[] = clazz.getMethods();
            for(Method method: methods) {
                Column methodAnno = method.getAnnotation(Column.class);
                if(methodAnno != null) {
                    String fieldNm = methodAnno.name().toUpperCase();
                    String[] obj = { tableNm, fieldNm };
                    list.add(obj);
                }
            }
        }

你可能感兴趣的:(Spring)