【问题标题】:how to remove the mapping resource property from hibernate.cfg file如何从 hibernate.cfg 文件中删除映射资源属性
【发布时间】:2010-06-05 05:28:51
【问题描述】:

我目前正在做一个项目。在我的项目中有很多实体/POJO 文件。目前我正在使用简单的 hibernate.cfg.xml 将所有映射文件添加到配置中,例如:-

<mapping resource="xml/ClassRoom.hbm.xml"/>
<mapping resource="xml/Teacher.hbm.xml"/>
<mapping resource="xml/Student.hbm.xml"/>

我有大量的映射文件,这使得我的 hibernate.cfg 文件看起来有点凌乱,所以有什么方法可以让我不需要将上述内容添加到 hibernate.cfg 文件中。而是可以有任何其他方法来实现相同的..请帮助

【问题讨论】:

    标签: hibernate hibernate-mapping


    【解决方案1】:

    您可以通过编程方式创建Configuration 并使用Configuration#addClass(Class) 指定映射类(Hibernate 将为您加载映射文件)。来自 javadoc:

    使用类的约定将映射作为应用程序资源读取 名为 foo.bar.Foo 的文件由 foo/bar/Foo.hbm.xml 映射 可以解析为类路径资源。

    所以你可以这样做:

    Configuration cfg = new Configuration()
        .addClass(org.hibernate.auction.Item.class)
        .addClass(org.hibernate.auction.Bid.class)
        ...
        .configure();
    SessionFactory factory = cfg.buildSessionFactory();
    

    另见

    【讨论】:

    • 只将“问题”转移到另一个地方。我想他想让hibernate神奇地理解他想要什么;)
    • @Bozho 真的。但是OP问有什么办法让我不需要将以上内容添加到hibernate.cfg.xml文件中,我的建议在使用映射文件时严格回答了这个问题:)
    • 确实如此。我的也是一个不错的选择,但让我们看看他会喜欢什么。
    【解决方案2】:

    Hibernate Configuration 类本身不提供神奇的 addAllEntities 方法。但是你可以使用AnnotationSessionFactoryBeansetPackagesToScan 方法。请记住,它仅在使用带注释的实体类时才有效,并且它是 Spring 依赖类

    AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean();
    
    sessionFactory.setDataSource(<javax.sql.DataSource> implementation goes here)
    sessionFactory.setPackagesToScan(new String [] {"xml"});
    

    【讨论】:

      【解决方案3】:

      是的,use annotations

      @Entity
      public class Teacher {
      
          @Column
          private String name;
      
          @Column
          private String address;
      
          etc..
      }
      

      Hibernate 将自动检测带有 @Entity 注释的类。

      【讨论】:

      • 嗨 Bozho .. 这很好,可以正常工作.. 但为此我需要更改类文件.. 这又是一项麻烦的工作.. 你能告诉我如何实现在我的项目中没有太大变化的情况下相同..
      • 没有办法。您必须在某处指定此信息。
      【解决方案4】:

      Configuration 的 addDirectory()/addJar() 方法使用在指定目录/JAR 文件中找到的所有 .hbm.xml 文件。你需要硬编码那个位置,但只有那个

      【讨论】:

        猜你喜欢
        • 2011-12-02
        • 2011-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-15
        • 1970-01-01
        • 1970-01-01
        • 2012-07-16
        相关资源
        最近更新 更多