I'm trying to use Hibernate 4 with annotations only, and a hibernate.cfg.xml
file. I've made my own annotation and am using reflection to add this to the configuration. I'm able to use Hibernate 4 in this manner fine, but my configuration is being built using a deprecated method.
final Configuration configuration = new Configuration();
final Reflections reflections = new Reflections(Item.class.getPackage().getName());
final Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Entity.class);
for (final Class<?> clazz : classes) {
configuration.addAnnotatedClass(clazz);
}
return configuration.configure().buildSessionFactory();
(Deprecated code: buildSessionFactory();
).
Even the hibernate 4 documentation shows to build the configuration in that manner.
If I try to use the new method (buildSessionFactory(ServiceRegistry)
, I don't get the same result, and it seems like a lot of unnecessary code to do exactly what the deprecated method does anyway. However, I don't want to keep using this style, because I dislike using deprecated code anyway.
My question is: How do I correctly configure Hibernate 4 from just a configuration file in the manner described above? I seem to just cause errors & face unnecessary difficulties.
@Entity annotation marks this class as an entity. @Table annotation specifies the table name where data of this entity is to be persisted. If you don't use @Table annotation, hibernate will use the class name as the table name by default.
@Entity annotation defines that a class can be mapped to a table. And that is it, it is just a marker, like for example Serializable interface.
The @Column annotation is defined as a part of the Java Persistence API specification. It's used mainly in the DDL schema metadata generation. This means that if we let Hibernate generate the database schema automatically, it applies the not null constraint to the particular database column.
The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database. The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table.
Modified code will look like below:-
final Configuration configuration = new Configuration();
final Reflections reflections = new Reflections(Item.class.getPackage().getName());
final Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Entity.class);
for (final Class<?> clazz : classes) {
configuration.addAnnotatedClass(clazz);
}
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings
(configuration.getProperties()).buildServiceRegistry();
return configuration.buildSessionFactory(serviceRegistry);
You may check following links for information: HHH-6183 and HHH-2578.
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