Can hibernate scan packages to create SessionFactory automatically?

后端 未结 2 1682
有刺的猬
有刺的猬 2021-01-11 15:49

Can I configure Hibernate to scan packages automatically to create a SessionFactory from @Entity annotated beans ?

Currently I am using

2条回答
  •  遥遥无期
    2021-01-11 16:55

    No. You can't say Hibernate to scan packages for persistent classes even with the last Hibernate 5 version. Configuration has method addPackage(), but it is for reading "package-level metadata" (.package-info- files).

    You don't want to use Spring, so what can you do:

    Using fluent-hibernate

    You can use EntityScanner from fluent-hibernate library (you will not need to have other jars, except the library)

    For Hibernate 4 and Hibernate 5:

    Configuration configuration = new Configuration();
    EntityScanner.scanPackages("my.com.entities", "my.com.other.entities")
        .addTo(configuration);
    SessionFactory sessionFactory = configuration.buildSessionFactory();
    

    Using a new Hibernate 5 bootstrapping API:

    List> classes = EntityScanner
            .scanPackages("my.com.entities", "my.com.other.entities").result();
    
    MetadataSources metadataSources = new MetadataSources();
    for (Class annotatedClass : classes) {
        metadataSources.addAnnotatedClass(annotatedClass);
    }
    
    SessionFactory sessionFactory = metadataSources.buildMetadata()
        .buildSessionFactory();
    

    Using other libraries

    If you already use a library that can be used for scanning, for an example Reflections, there is a test project with examples of using various libraries for entity scanning: hibernate-scanners-test.

提交回复
热议问题