Can I configure Hibernate to scan packages automatically to create a SessionFactory
from @Entity
annotated beans ?
Currently I am using
Configuration config = new Configuration() ;
config.addAnnotatedClass(MyEntity.class);
I do not want to use hibernate.cfg.xml
to configure mappings.
Please note I want to achieve this in a plain Java project without using any Spring or such frameworks.
Similar question have been answered using Spring before but I want to achieve it without using Spring or other frameworks. I am open to some simple library that does this.
Hibernate SessionFactory is an interface. It can be created through providing objects of Configuration. This will contain all the database property details which are pulled from either hibernate. properties file or hibernate.
Configuration object is used to create a SessionFactory object.
In hibernate we can interact with multiple databases within the same application. All we need is to create two different session factories; one to interact with each database.
You would need one SessionFactory object per database using a separate configuration file. So, if you are using multiple databases, then you would have to create multiple SessionFactory objects.
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<Class<?>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With