簡體   English   中英

通過在某個包中添加所有類,在 Hibernate 中添加帶注釋的類。 爪哇

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

有什么方法可以循環(例如通過 for)所有類都在某個包中? 我必須在AnnotationConfigurationaddAnnotatedClass(Class c) 這樣做:

    AnnotationConfiguration annotationConfiguration.addAnnotatedClass(AdditionalInformation.class);
    annotationConfiguration.addAnnotatedClass(AdditionalInformationGroup.class);
    annotationConfiguration.addAnnotatedClass(Address.class);
    annotationConfiguration.addAnnotatedClass(BankAccount.class);
    annotationConfiguration.addAnnotatedClass(City.class);
    //et cetera

我所有的表都在包Tables.Informations

如評論中所述,使用 AnnotationConfiguration API 無法實現在包中加載所有類的功能。 以下是您可以使用上述 API 執行的一些操作(請注意,“addPackage”方法僅讀取包元數據,例如在 package-info.java 類中找到的元數據,它不會加載包中的所有類):

http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/ch01.html

sessionFactory = new AnnotationConfiguration()
                    .addPackage("test.animals") //the fully qualified package name
                    .addAnnotatedClass(Flight.class)
                    .addAnnotatedClass(Sky.class)
                    .addAnnotatedClass(Person.class)
                    .addAnnotatedClass(Dog.class)
                    .addResource("test/animals/orm.xml")
                    .configure()
                    .buildSessionFactory();

以下代碼遍歷指定包中的所有類,並列出用“@Entity”注釋的類。 這些類中的每一個都被添加到您的 Hibernate 工廠配置中,而不必明確列出它們。

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<Class<?>> getEntityClassesFromPackage(String packageName) throws ClassNotFoundException, IOException, URISyntaxException {
    List<String> classNames = getClassNamesFromPackage(packageName);
    List<Class<?>> classes = new ArrayList<Class<?>>();
    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<String> getClassNamesFromPackage(String packageName) throws IOException, URISyntaxException, ClassNotFoundException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    ArrayList<String> names = new ArrayList<String>();

    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;
}

有用的參考: https : //stackoverflow.com/a/7461653/7255

有一個很好的開源包叫做“org.reflections”。 你可以在這里找到它: https : //github.com/ronmamo/reflections

使用該包,您可以掃描這樣的實體:

Reflections reflections = new Reflections("Tables.Informations");
Set<Class<?>> importantClasses = reflections.getTypesAnnotatedWith(Entity.class);
for (Class<?> clazz : importantClasses) {
    configuration.addAnnotatedClass(clazz);
}

您可以使用LocalSessionFactoryBuilder來構建會話工廠,使您能夠指定scanPackages屬性。

SessionFactory sessionFactory = new LocalSessionFactoryBuilder(hikariDataSource())
        .scanPackages("com.animals.entities")
        .addProperties(properties)
        .buildSessionFactory();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM