从休眠类获取名称

时间:2018-12-19 11:04:58

标签: java hibernate annotations

我有一个支持XML-config的项目。现在,我们想通过注释为实体添加休眠配置。似乎有可能并且有效(如果我输入错了,请纠正我)。问题是我们的系统

private String entityName() {
    String name = null;
    try {
        String longName = getDaoFactory().getSessionFactory().getClassMetadata(entityClass).getEntityName();
        name = longName.substring(longName.lastIndexOf(".") + 1);
    } catch (Exception ex) {
        log.error("Exception getting name from hibernate for class: " + entityClass);
        name = null;
    }
    return name;
}

此方法对于具有xml-config的实体效果很好,但是如何获取通过注释配置的实体的名称?

在此先感谢您的任何建议:)

UPD:

通过初始化会话工厂方法:

Configuration configuration = new Configuration(); 
configuration.addResource("resources/administrator/queries.hbm.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration
        .getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
setSessionFactory(sessionFactory);
return configuration;

1 个答案:

答案 0 :(得分:0)

I created a session Factory like this.

public static SessionFactory buildSessionFactoryFromAnnotatedClasses(){
    StandardServiceRegistry standardRegistry =
        new StandardServiceRegistryBuilder().applySettings(// pass org.hibernate.cfg.Configuration object here)
            .getProperties()).build(); // Configuration object has properties

    MetadataSources sources = new MetadataSources(standardRegistry);
    sources.addAnnotatedClass(MyClass.class);// MyClass is your java annotated class
    Metadata metaData = sources.getMetadataBuilder().build();
    return metaData.getSessionFactoryBuilder().build();
  }