【问题标题】:How to retrieve relationship mapping in hibernate?如何在hibernate中检索关系映射?
【发布时间】:2014-11-14 15:54:00
【问题描述】:

我需要获取两个模型类之间的关系。 例如 在数据库中,我有两个表 table1 和 table2。其中 table2 具有 table1 的外键。 我有两个类 Table1 和 Table2 分别映射到这些表,并且具有一对一的关系映射。

现在,我需要从 java 代码中检索它们之间的关系?即上述示例的输出应该是一对一的。

【问题讨论】:

    标签: java hibernate


    【解决方案1】:

    我准备了这个演示来查找两个休眠实体类之间的关联类型。它可能会帮助其他社区用户发布此答案。

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.util.Map;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.metadata.ClassMetadata;
    import org.hibernate.metadata.CollectionMetadata;
    import org.hibernate.persister.collection.BasicCollectionPersister;
    import org.hibernate.persister.collection.OneToManyPersister;
    import org.hibernate.service.ServiceRegistryBuilder;
    import org.hibernate.type.ManyToOneType;
    import org.hibernate.type.OneToOneType;
    import org.hibernate.type.Type;
    
    /**
     *
     * @author shruti
     */
    public class RelationDemo {
    
        public static void main(String[] args) throws Exception {
    
            Configuration configuration = new Configuration().configure();
            ServiceRegistryBuilder builder = new ServiceRegistryBuilder().applySettings(configuration.getProperties());
            SessionFactory sessionfactory = configuration.buildSessionFactory(builder.buildServiceRegistry());
    
            //1. Read class names
            System.out.println("Enter first class names (make sure you enter fully qualified name): ");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            String class1 = bufferedReader.readLine();
            System.out.println("Enter second class names (make sure you enter fully qualified name): ");
            String class2 = bufferedReader.readLine();
    
            ClassMetadata classMetadata = null;
    
            //2. Create ClassMetaData for the first class name and check that both the classes exists.
            try {
                classMetadata = sessionfactory.getClassMetadata(Class.forName(class1));
                Class.forName(class2);
            } catch (ClassNotFoundException classNotFoundException) {
                System.err.println("Invalid class name.\nHint: Enter fully qualified class names for eg. packagename.Classname");
                classNotFoundException.printStackTrace(System.err);
                return;
            }
    
            //3. Retrieve all collection metada for collection type properties
            @SuppressWarnings("unchecked")
            Map<String, CollectionMetadata> allCollectionMetadata = sessionfactory.getAllCollectionMetadata();
    
            //Retrieve all properties of the first class
            String[] propertyNames = classMetadata.getPropertyNames();
    
            //Loop through the retrieved properties
            for (String name : propertyNames) {
    
                //Retrieve type of each property
                Type type = classMetadata.getPropertyType(name.trim());
    
                //Check if the type is association type
                if (type.isAssociationType()) {
    
                    //Check if it is collection type.
                    if (type.isCollectionType()) {
    
                        //From retrieved collection metadata (Strp 3) get value of the property we are refering to.
                        CollectionMetadata collectionMetadata = allCollectionMetadata.get(class1 + "." + name);
    
                        //Check if the elements of the collection are of desiered type
                        if (collectionMetadata.getElementType().getName().trim().equals(class2)) {
                            System.out.println("Property Name: " + name);
                            //Check if the value is of type OneToManyPersister
                            if (collectionMetadata instanceof OneToManyPersister) {
                                System.out.println("ONE TO MANY TYPE");
                                return;
                            } //Check if the value is of type BasicCollectionPersister. Note that for many to many relationship it would return an object of type BasicCollectionPersister.
                            else if (collectionMetadata instanceof BasicCollectionPersister) {
                                if (((BasicCollectionPersister) collectionMetadata).isManyToMany()) {
                                    System.out.println("MANY TO MANY");
                                }
                            }
                        }
                    } //If property is not a collection then retrieve the class of the type and check if it is the same as Second class.
                    else if (type.getReturnedClass().getTypeName().equals(class2)) {
                        System.out.println("Property Name: " + name);
                        if (type instanceof ManyToOneType) {
                            System.out.println("MANY TO ONE TYPE");
                            return;
                        } else if (type instanceof OneToOneType) {
                            System.out.println("ONE TO ONE TYPE");
                            return;
                        }
                    }
                }
            }
            System.out.println("NO RELATIONSHIP FOUND BETWEEN GIVEN CLASSES");
        }
    }
    

    【讨论】:

      【解决方案2】:

      Hibernate 有元数据包 org.hibernate.metadta 可以帮助你。 请参阅 https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/metadata/ClassMetadata.html

      【讨论】:

        【解决方案3】:

        您可以尝试以下代码,该代码显示了实体可用的集合详细信息:

        Map<String,CollectionMetadata> map = sessionFactory.getAllCollectionMetadata();
                Set<Entry<String,CollectionMetadata>> set = map.entrySet();
                for (Entry e : set) {
                    System.out.println(e.getKey());
                    System.out.println(e.getValue());
                }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-16
          • 2012-02-08
          • 1970-01-01
          • 2020-10-11
          • 2020-12-04
          • 2013-05-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多