Add Annotated Class in Hibernate by adding all classes in some package. JAVA

后端 未结 4 934
旧时难觅i
旧时难觅i 2020-12-15 00:40

is there any way to loop (e.g. via for) all classes with are in some package? I have to addAnnotatedClass(Class c) on AnnotationConfigura

4条回答
  •  感动是毒
    2020-12-15 01:17

    The following code goes through all the classes within a specified package and makes a list of those annotated with "@Entity". Each of those classes is added into your Hibernate factory configuration, without having to list them all explicitly.

    public static void main(String[] args) throws URISyntaxException, IOException, ClassNotFoundException {
        try {
            Configuration configuration = new Configuration().configure();
            for (Class cls : getEntityClassesFromPackage("com.example.hib.entities")) {
                configuration.addAnnotatedClass(cls);
            }
            sessionFactory = configuration.buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static List> getEntityClassesFromPackage(String packageName) throws ClassNotFoundException, IOException, URISyntaxException {
        List classNames = getClassNamesFromPackage(packageName);
        List> classes = new ArrayList>();
        for (String className : classNames) {
            Class cls = Class.forName(packageName + "." + className);
            Annotation[] annotations = cls.getAnnotations();
    
            for (Annotation annotation : annotations) {
                System.out.println(cls.getCanonicalName() + ": " + annotation.toString());
                if (annotation instanceof javax.persistence.Entity) {
                    classes.add(cls);
                }
            }
        }
    
        return classes;
    }
    
    public static ArrayList getClassNamesFromPackage(String packageName) throws IOException, URISyntaxException, ClassNotFoundException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        ArrayList names = new ArrayList();
    
        packageName = packageName.replace(".", "/");
        URL packageURL = classLoader.getResource(packageName);
    
        URI uri = new URI(packageURL.toString());
        File folder = new File(uri.getPath());
        File[] files = folder.listFiles();
        for (File file: files) {
            String name = file.getName();
            name = name.substring(0, name.lastIndexOf('.'));  // remove ".class"
            names.add(name);
        }
    
        return names;
    }
    

    Helpful reference: https://stackoverflow.com/a/7461653/7255

提交回复
热议问题