简体   繁体   English

未在cfg中映射的休眠加载实体

[英]Hibernate loading Entities that are not mapped in cfg

I have been using Hibernate for some time with great success. 我使用Hibernate已有一段时间,并取得了巨大的成功。 However I ran into an issue yesterday and an answer here would save a lot of debugging time in the future. 但是我昨天遇到了一个问题,这里的答案将在将来节省大量调试时间。

I forgot to add a hibernate mapping to my hibernate.cfg for a new Entity. 我忘记为我的hibernate.cfg添加新的实体的休眠映射。

I would have expected to get some sort of run time exception when I tried to load this entity, but instead it just loaded nothing and continued as if everything was fine. 当我尝试加载该实体时,我本来希望得到某种运行时异常,但是相反,它什么也没有加载,就好像一切都很好一样继续进行。

I am using the following code to load the entities. 我正在使用以下代码加载实体。

protected List<T> findByCriteria(Session session, Criterion... criterion) {
    Criteria crit = session.createCriteria(getPersistentClass()); /getPersistentClass returns a Class<T>
    for (Criterion c : criterion) {
        crit.add(c);
    }
    return crit.list();
}

I would like an error if I try an load an Entity that is not mapped in my hibernate.cfg. 如果我尝试加载未在hibernate.cfg中映射的实体,我想报错。

Is there a way to do this? 有没有办法做到这一点?

Are you running your code in j2EE server. 您是否正在j2EE服务器中运行代码。 As posted in previous answer are you using annotations on your entity class ? 如先前答案中所述,您是否在实体类上使用注释? If so try removing entity annotation. 如果是这样,请尝试删除实体注释。

In the end, I abandoned the mappings in the hibernate.cfg and added the following method when building the Configuration object for my SessionFactory. 最后,在为SessionFactory构建Configuration对象时,我放弃了hibernate.cfg中的映射,并添加了以下方法。

private static void addAnnotatedEntityClasses(Configuration configuration) {
    Reflections reflections = new Reflections("com.mypackage");
    Set<Class<?>> classes = reflections.getTypesAnnotatedWith(Entity.class);

    logger.debug("Adding Hibernate Mapping for: ");
    for (final Class<?> clazz : classes) {
        logger.debug(clazz.getName());
        configuration.addAnnotatedClass(clazz);
    }
}

This finds all classes in my project with the Entity annotation and adds a mapping. 这将找到项目中带有Entity批注的所有类,并添加一个映射。

This uses the Reflections library for simplicity. 为了简单起见,这使用了反射库。 Found here: 在这里找到:

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.9-RC1</version>
</dependency>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM