gpt4 book ai didi

java - Hibernate 配置未列出 XML 中的所有实体

转载 作者:行者123 更新时间:2023-11-30 02:57:03 25 4
gpt4 key购买 nike

目前在我的 hibernate.cfg.xml 文件中,我必须将每个单独的实体列为映射类,以便我的 Hibernate 能够获取该实体,否则我会收到类似 references an unknown entity 的错误。

所以我有大约 20 行:

<mapping class="my.com.entity.User"></mapping>
<mapping class="my.com.entity.Address"></mapping>
...

有没有办法告诉 Hibernate“嘿,只需将 my.com.entity 包中的所有内容作为实体拉入”,而不是每次创建新实体时都在 XML 文件中添加新行?

最佳答案

没有。即使使用最新的 Hibernate 5 版本,也不能让 Hibernate 扫描包中的持久类。

使用Spring

使用 Spring 的常见方法,如 @Srini 建议的那样。

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="packagesToScan">
<list>
<value>my.com.entities</value>
<value>my.com.other.entities</value>
</list>
</property>
</bean>

请注意,根据 Hibernate 版本,您需要使用包:org.springframework.orm.hibernate5org.springframework.orm.hibernate4

使用 Fluent-Hibernate

如果你不想使用Spring,你可以使用 EntityScanner来自fluent-hibernate库(除了库之外,您不需要其他 jar )。除此之外,它还具有一些对 Hibernate 5 和 Hibernate 4 有用的功能,包括实体扫描、Hibernate 5 隐式命名策略、嵌套转换器等。

对于 Hibernate 4 和 Hibernate 5:

Configuration configuration = new Configuration();
EntityScanner.scanPackages("my.com.entities", "my.com.other.entities")
.addTo(configuration);
SessionFactory sessionFactory = configuration.buildSessionFactory();

使用新的 Hibernate 5 引导 API:

List<Class<?>> classes = EntityScanner
.scanPackages("my.com.entities", "my.com.other.entities").result();

MetadataSources metadataSources = new MetadataSources();
for (Class<?> annotatedClass : classes) {
metadataSources.addAnnotatedClass(annotatedClass);
}

SessionFactory sessionFactory = metadataSources.buildMetadata()
.buildSessionFactory();

使用其他库

如果您已经使用可用于扫描的库,例如 Reflections ,有一个测试项目,其中包含使用各种库进行实体扫描的示例:hibernate-scanners-test

关于java - Hibernate 配置未列出 XML 中的所有实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36972953/

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