通过在某个包中添加所有类,在Hibernate中添加带注释的类.JAVA

Mic*_*óra 7 java hibernate

有没有办法循环(例如,通过)所有类在一些包中? 我必须addAnnotatedClass(Class c)AnnotationConfiguration.这样做:

    AnnotationConfiguration annotationConfiguration.addAnnotatedClass(AdditionalInformation.class);
    annotationConfiguration.addAnnotatedClass(AdditionalInformationGroup.class);
    annotationConfiguration.addAnnotatedClass(Address.class);
    annotationConfiguration.addAnnotatedClass(BankAccount.class);
    annotationConfiguration.addAnnotatedClass(City.class);
    //et cetera
Run Code Online (Sandbox Code Playgroud)

我的所有桌子都是包装好的Tables.Informations.

Shi*_*gon 13

正如评论中所提到的,使用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();
Run Code Online (Sandbox Code Playgroud)

  • 这究竟是如何解决必须在实用程序类中的类名中进行刻录的问题?(它只节省了几次击键). (3认同)
  • @vbence是的,同意,对不起,我的答案是错的:使用AnnotationConfiguration API无法一次性添加一个包中的所有类.我给出的示例应该说明您可以执行此操作,以及一次性添加单个类和其他资源.我basicaly对的API相同误解为一个在这里讨论:https://forum.hibernate.org/viewtopic.php?f=1&t=980723我希望我能删除我的帖子,但我不能,因为这是一个公认的答案. (3认同)
  • 哦,我看了那个(论坛帖子).也许你可以添加一个类似*的注释"它不可能是OP原始想要的,但这种语法有点"*或类似的东西. (2认同)

Ste*_*ers 7

以下代码遍历指定包中的所有类,并列出使用"@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;
}
Run Code Online (Sandbox Code Playgroud)

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


Mat*_*len 5

有一个很好的开源包,名为“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);
}
Run Code Online (Sandbox Code Playgroud)