【问题标题】:Get column name of property mapped with Hibernate获取使用 Hibernate 映射的属性的列名
【发布时间】:2010-01-07 21:10:21
【问题描述】:

如何访问模型的 Hibernate 映射以找出属性的列名?

映射中未指定列名,因此 Hibernate 会自动生成它 - 我想创建一个包含该列名的本机 SQL 语句。

【问题讨论】:

    标签: java sql hibernate


    【解决方案1】:

    感谢 Jherico,我知道了如何做到这一点:

    ((Column) sessionFactoryBean.getConfiguration().getClassMapping(Person.class.getName())
            .getProperty("myProperty").getColumnIterator().next()).getName();
    

    【讨论】:

    • 这里的“sessionFactoryBean”是什么?我确定它不是 sessionFactory。
    • 可以是sessionFactory也可以是SessionFactoryBean,视版本而定
    【解决方案2】:
    ((AbstractEntityPersister) sessionFactory.getClassMetadata(o.getClass()))
        .getPropertyColumnNames(property)[0];
    

    【讨论】:

    • 如果o 是代理,您应该使用Hibernate.getClass(o) 而不是o.getClass()
    【解决方案3】:

    您必须有权访问 Hibernate 配置对象。

    【讨论】:

      【解决方案4】:

      这将检索一级复合和普通属性映射:

      String columnName(String name) {
          PersistentClass mapping = configuration.getClassMapping(ExtendedPerson.class.getName());
          Property property = mapping.getProperty(name);
          if(property.isComposite()){
              Component comp = (Component) property.getValue();
              property = comp.getProperty(StringHelper.unroot(name));
              assert ! property.isComposite(); //go only one level down 
          }
          Iterator<?> columnIterator = property.getColumnIterator();
          Column col = (Column) columnIterator.next();
          assert ! columnIterator.hasNext();
          return col.getName();
      }
      

      【讨论】:

        猜你喜欢
        • 2012-01-30
        • 2013-02-10
        • 2013-04-23
        • 2023-03-20
        • 2011-06-22
        • 1970-01-01
        • 2014-07-07
        • 2012-02-12
        • 2013-03-07
        相关资源
        最近更新 更多