有什么方法可以循环(例如通过for)某个包中的所有类吗? 我必须
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
我所有的桌子都在包装中
Tables.Informations
。
正如评论中提到的,使用 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();
以下代码遍历指定包中的所有类,并列出用“@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;
}
有一个很好的开源包,名为“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);
}
您可以使用 LocalSessionFactoryBuilder 来构建会话工厂,使您能够指定 scanPackages 属性。
SessionFactory sessionFactory = new LocalSessionFactoryBuilder(hikariDataSource())
.scanPackages("com.animals.entities")
.addProperties(properties)
.buildSessionFactory();
对于 Hibernate 6.* 版本,实现方法是:
public class HibernateUtils {
private static SessionFactory sessionFactory;
static {
try {
Properties props = new Properties();
props.load(HibernateUtils.class.getClassLoader().getResourceAsStream("hibernate.properties"));
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(props)
.build();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
Reflections reflections = new Reflections("io.github.gustavo.model");
Set<Class<?>> entityClasses = reflections.getTypesAnnotatedWith(Entity.class);
entityClasses.forEach(metadataSources::addAnnotatedClass);
Metadata metadata = metadataSources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
} catch(Exception e) {
throw new ExceptionInInitializerError("Falha ao inicializar a Session Factory");
}
}
lib 反思:
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>