问题描述
我正在使用 Hibernate 注释.
I'm using Hibernate Annotations.
在我所有的模型类中,我都这样注释:
In all my model classes I annotate like this:
@Entity
@Table
public class SomeModelClass {
//
}
我的 hibernate.cfg.xml 是
My hibernate.cfg.xml is
<hibernate-configuration>
<session-factory>
<!-- some properties -->
<mapping package="com.fooPackage" />
<mapping class="com.fooPackage.SomeModelClass" />
</session-factory>
</hibernate-configuration>
对于我添加到 com.fooPackage 的每个类,我必须在 hibernate.cfg.xml 中添加一行,如下所示:
For every class I add to the com.fooPackage I have to add a line in the hibernate.cfg.xml like this:
<mapping class="com.fooPackage.AnotherModelClass" />
有没有办法可以添加新的模型类但不需要将此行添加到 hibernate.cfg.xml 中?
Is there a way I can add new model classes but don't need to add this line to hibernate.cfg.xml?
推荐答案
开箱即用 - 没有.但是,您可以编写自己的代码来检测/注册带注释的类.如果您使用的是 Spring,则可以扩展 AnnotationSessionFactoryBean
并执行以下操作:
Out of the box - no. You can write your own code to detect / register your annotated classes, however. If you're using Spring, you can extend AnnotationSessionFactoryBean
and do something like:
@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
中注册它们/code> 方法.
If you're not using Spring (and you should be :-) ) you can write your own code for detecting appropriate classes and register them with your AnnotationConfiguration
via addAnnotatedClass()
method.
顺便说一句,除非您确实在包级别声明了某些内容,否则没有必要映射包.
Incidentally, it's not necessary to map packages unless you've actually declared something at package level.
这篇关于Hibernate 映射包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!