使用ClassMetadata确定ManyToMany与OneToMany [英] Determining ManyToMany vs OneToMany using ClassMetadata

查看:116
本文介绍了使用ClassMetadata确定ManyToMany与OneToMany的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ClassMetadata来确定一个hibernate POJO的结构。

I am using ClassMetadata to determine the structure of a hibernate POJO.

我需要确定一个集合是OneToMany还是ManyToMany。这些信息在哪里?我可以在不使用反射的情况下使用它吗?看到我的代码如下。

I need to determine if a collection is OneToMany or ManyToMany. Where is this information? Can I get to it without using reflection? See my code below.


//Get the class' metadata
ClassMetadata cmd=sf.getClassMetadata(o.getClass());

for(String propertyName:cmd.getPropertyNames()){
    if (cmd.getPropertyType(propertyName).isCollectionType() && cmd.??()) //Do something with @ManyToMany collections.
}

我需要的是告诉我它是否是ManyTo____关系的方法。我看到getPropertyLaziness(),但这并不总是保证集合的类型。任何想法?

All I need is method to tell me if it's a ManyTo____ relationship. I see getPropertyLaziness(), but that doesn't always guarantee the type of collection. Any ideas?

推荐答案

这并不那么简单,不幸的是。检测这种情况的最佳方法是检查特定的 CollectionPersister 实现:

It's not that simple, unfortunatelly. Your best bet to detect this is by checking for particular CollectionPersister implementation:

SessionFactory sf = ...;

// Get the class' metadata
ClassMetadata cmd = sf.getClassMetadata(o.getClass());

for(String propertyName:cmd.getPropertyNames()) {
  Type propertyType = cmd.getPropertyType(propertyName);
  if (propertyType.isCollectionType()) {
    CollectionType collType = (CollectionType) propertyType;

    // obtain collection persister
    CollectionPersister persister = ((SessionFactoryImplementor) sf)
      .getCollectionPersister(collType.getRole());

    if (persister instanceof OneToManyPersister) {
      // this is one-to-many
    } else {
     // this is many-to-many OR collection of elements
    }
  } // if
} // for

这篇关于使用ClassMetadata确定ManyToMany与OneToMany的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆