All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ibankapp.base.persistence.domain.EntityInformation Maven / Gradle / Ivy

There is a newer version: 1.0.0-beta.6
Show newest version
/*
 * iBankApp
 *
 * License : Apache License,Version 2.0, January 2004
 *
 * See the LICENSE file in English or LICENSE.zh_CN in chinese
 * in the root directory or .
 */

package org.ibankapp.base.persistence.domain;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.IdentifiableType;
import javax.persistence.metamodel.ManagedType;
import javax.persistence.metamodel.Metamodel;
import javax.persistence.metamodel.SingularAttribute;

/**
 * 实体信息类,通过此类的方法可获得实体类的一些静态信息
 *
 * @param  实体类
 * @author ibankapp
 * @author codelder
 * @since 1.0.0
 */
public class EntityInformation {

    private final IdMetadata idMetadata;
    private String entityName;

    /**
     * 构造函数
     *
     * @param domainClass 实体类CLASS
     * @param metamodel   模型元数据,可从jpa的实体管理器EntityManage获取
     */
    public EntityInformation(Class domainClass, Metamodel metamodel) {

        ManagedType type = metamodel.managedType(domainClass);

        this.entityName = ((EntityType) type).getName();

        IdentifiableType identifiableType = (IdentifiableType) type;

        this.idMetadata = new IdMetadata(identifiableType);
    }

    /**
     * 获取实体类的名称
     *
     * @return 实体类名称
     */
    public String getEntityName() {
        return entityName;
    }

    /**
     * 获取实体类的id属性列表
     *
     * @return id属性列表
     */
    public Iterable getIdAttributeNames() {

        List attributeNames = new ArrayList(idMetadata.attributes.size());

        for (SingularAttribute attribute : idMetadata.attributes) {
            attributeNames.add(attribute.getName());
        }
//        attributeNames.addAll(idMetadata.attributes.stream().map(Attribute::getName).collect(Collectors.toList()));

        return attributeNames;
    }

    /**
     * Id元数据内部类
     */
    private static class IdMetadata {

        /**
         * id所包含的属性字段
         */
        private final Set> attributes;


        /**
         * 构造函数
         *
         * @param source id类型
         */
        @SuppressWarnings("unchecked")
        IdMetadata(IdentifiableType source) {

            this.attributes = (Set>) (source.hasSingleIdAttribute()
                    ? Collections.singleton(source.getId(source.getIdType().getJavaType()))
                    : source.getIdClassAttributes());
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy