gpt4 book ai didi

java - Hibernate 映射包

转载 作者:IT老高 更新时间:2023-10-28 20:47:07 24 4
gpt4 key购买 nike

我正在使用 Hibernate 注释。

在我的所有模型类中,我都这样注释:

@Entity
@Table
public class SomeModelClass {
//
}

我的hibernate.cfg.xml是

<hibernate-configuration>
<session-factory>
<!-- some properties -->

<mapping package="com.fooPackage" />
<mapping class="com.fooPackage.SomeModelClass" />
</session-factory>
</hibernate-configuration>

对于我添加到 com.fooPackage 的每个类,我必须在 hibernate.cfg.xml 中添加一行,如下所示:

<mapping class="com.fooPackage.AnotherModelClass" />

有没有办法可以添加新的模型类但不需要将此行添加到 hibernate.cfg.xml?

最佳答案

开箱即用 - 不。但是,您可以编写自己的代码来检测/注册带注释的类。如果您使用的是 Spring,则可以扩展 AnnotationSessionFactoryBean 并执行以下操作:

@Override
protected SessionFactory buildSessionFactory() throws Exception {
ArrayList<Class> classes = new ArrayList<Class>();

// the following will detect all classes that are annotated as @Entity
ClassPathScanningCandidateComponentProvider scanner =
new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

// only register classes within "com.fooPackage" package
for (BeanDefinition bd : scanner.findCandidateComponents("com.fooPackage")) {
String name = bd.getBeanClassName();
try {
classes.add(Class.forName(name));
} catch (Exception E) {
// TODO: handle exception - couldn't load class in question
}
} // for

// register detected classes with AnnotationSessionFactoryBean
setAnnotatedClasses(classes.toArray(new Class[classes.size()]));
return super.buildSessionFactory();
}

如果你没有使用 Spring(你应该是:-))你可以编写你自己的代码来检测适当的类,并通过 addAnnotatedClass()< 在你的 AnnotationConfiguration 中注册它们 方法。

顺便说一句,除非您实际上在包级别声明了某些内容,否则没有必要映射包。

关于java - Hibernate 映射包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1413190/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com