Loading multiple annotated classes in Hibernate

I use annotations for sleep mode, and for this in hibernate.cfg.xml I need to add annotated classes such as this <mapping class="p.Customer" /> here p is the package name and Client . annotated bean.

Suppose I have 20 such annotated classes, which means that I have to write 20 mapping lines for this class. In Spring, there is a packageToScan property that can be used to register / load all hibernate annotated classes into the specified package.

Since I do not use Spring, can we have the same functionality in Hibernate?

Also I found one tag in hibernate.cfg.xml <mapping package="" /> at first, I thought this would do the job for me, but that didn't work. I did not get what uses this property.

+4
source share
2 answers

The magic of annotation parsing is performed when creating a factory session. Hibernate can do this without spring. Spring actually just wraps the sleep mode functionality.

Please take a look at this article: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-overview

They show how to register classes in a factory session, so annotations are used. They really do not provide scanning functionality, but you can either implement it yourself, or it is better to use another package. I used the reflection package for a similar purpose. I mean, I went through my class path to find classes according to my criteria using a reflection package. I did not use it for sleep mode, but I am sure that this is possible.

Here is a link that might help you. http://code.google.com/p/reflections/

+1
source

1, see How to get all class names in a package?

2 continue with org.hibernate.cfg.Configuration

`

 package com.hw.configuration; import com.hw.util.ClassFinder; import org.hibernate.MappingException; import org.hibernate.cfg.Configuration; import java.util.List; /** * Created by whuanghkl on 17/5/31. */ public class WildCardConfiguration extends Configuration { @Override public Configuration addPackage(String packageName) throws MappingException { List<Class<?>> classes = ClassFinder.find(packageName); int size=classes.size(); for (int i=0;i<size;i++){ super.addAnnotatedClass(classes.get(i)); } return this; } } 

`

3, `

 new SchemaExport(new WildCardConfiguration().configure()).create(true, false); 

`

0
source

Source: https://habr.com/ru/post/1434463/


All Articles