可以休眠扫描包来自动创建SessionFactory? [英] Can hibernate scan packages to create SessionFactory automatically?
本文介绍了可以休眠扫描包来自动创建SessionFactory?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以配置Hibernate自动扫描包以从 @Entity
带注释的bean中创建 SessionFactory
吗?
目前我正在使用
Configuration config = new Configuration() ;
config.addAnnotatedClass(MyEntity.class);
我不想使用 hibernate.cfg.xml
来配置映射。
请注意我想在一个普通的Java项目中实现这个功能,而不使用任何Spring或这样的框架。
以前用Spring回答过类似的问题,但我想在不使用Spring或其他框架的情况下实现它。我向一些简单的图书馆开放,可以做到这一点。
解决方案
没有。即使使用最后一个Hibernate 5版本,你也不能说Hibernate为持久化类扫描软件包。 配置
有方法 addPackage()
,但它是用于读取包级别元数据( .package-info
- files)。
你不想使用Spring,那么你该怎么做:
使用流利hibernate
您可以使用
EntityScanner from fluent-hibernate 库(您不需要除了库之外,还有其他的jar)
对于Hibernate 4和Hibernate 5:
Configuration configuration = new Configuration();
EntityScanner.scanPackages(my.com.entities,my.com.other.entities)
.addTo(配置);
SessionFactory sessionFactory = configuration.buildSessionFactory();
使用新的Hibernate 5引导API:
List< Class<?>> classes = EntityScanner
.scanPackages(my.com.entities,my.com.other.entities)。result();
MetadataSources metadataSources = new MetadataSources(); (Class<> annotatedClass:classes){
metadataSources.addAnnotatedClass(annotatedClass);
;
SessionFactory sessionFactory = metadataSources.buildMetadata()
.buildSessionFactory();
使用其他库
如果您已经使用可用于扫描的库,例如思考,那里是一个测试项目,其中包含使用各种库进行实体扫描的示例: hibernate-scanners-test