国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 Java java教程 將 JPA 實體轉(zhuǎn)換為 Mendix

將 JPA 實體轉(zhuǎn)換為 Mendix

Jan 13, 2025 pm 06:04 PM

最近在探索 Mendix 時,我注意到他們有一個 Platform SDK,允許您通過 API 與 mendix 應用程序模型進行交互。

這給了我一個想法,探索它是否可以用于創(chuàng)建我們的領(lǐng)域模型。具體來說,是基于現(xiàn)有的傳統(tǒng)應用程序創(chuàng)建領(lǐng)域模型。

如果進一步推廣,這可用于將任何現(xiàn)有應用程序轉(zhuǎn)換為 Mendix 并從那里繼續(xù)開發(fā)。

將 Java/Spring Web 應用程序轉(zhuǎn)換為 Mendix

因此,我創(chuàng)建了一個帶有簡單 API 和數(shù)據(jù)庫層的小型 Java/Spring Web 應用程序。為了簡單起見,它使用嵌入式 H2 數(shù)據(jù)庫。

在這篇文章中,我們將僅轉(zhuǎn)換 JPA 實體。讓我們來看看它們:

@Entity
@Table(name = "CAT")
class Cat {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private int age;
    private String color;

    @OneToOne
    private Human humanPuppet;

    ... constructor ...
    ... getters ...
}

@Entity
@Table(name = "HUMAN")
public class Human {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    ... constructor ...
    ... getters ...
}

如您所見,它們非常簡單:一只有名字、年齡、顏色的貓和它的人類傀儡,因為正如我們所知,貓統(tǒng)治著世界。

它們都有一個自動生成的 ID 字段。貓與人類有一對一的聯(lián)系,這樣它就可以隨時稱呼它的人類。 (如果它不是 JPA 實體,我會放置一個 meow() 方法,但讓我們將其留到將來)。

應用程序功能齊全,但現(xiàn)在我們只對數(shù)據(jù)層感興趣。

提取 json 中的實體元數(shù)據(jù)

這可以通過幾種不同的方式來完成:

  1. 通過靜態(tài)分析包中的實體。
  2. 通過使用反射在運行時讀取這些實體。

我選擇了選項 2,因為它更快,而且我無法輕松找到可以執(zhí)行選項 1 的庫。

接下來,我們需要決定構(gòu)建后如何公開 json。為了簡單起見,我們只需將其寫入文件即可。一些替代方法可能是:

  • 通過 api 公開它。這更加復雜,因為您還需要確保端點受到很好的保護,因為我們不能公開暴露我們的元數(shù)據(jù)。
  • 通過一些管理工具公開它,例如 Spring Boot Actuator 或 jmx。它更安全,但仍然需要時間來設(shè)置。

現(xiàn)在讓我們看看實際的代碼:

public class MendixExporter {
    public static void exportEntitiesTo(String filePath) throws IOException {
        AnnotatedTypeScanner typeScanner = new AnnotatedTypeScanner(false, Entity.class);

        Set<Class<?>> entityClasses = typeScanner.findTypes(JavaToMendixApplication.class.getPackageName());
        log.info("Entity classes are: {}", entityClasses);

        List<MendixEntity> mendixEntities = new ArrayList<>();

        for (Class<?> entityClass : entityClasses) {
            List<MendixAttribute> attributes = new ArrayList<>();
            for (Field field : entityClass.getDeclaredFields()) {

                AttributeType attributeType = determineAttributeType(field);
                AssociationType associationType = determineAssociationType(field, attributeType);
                String associationEntityType = determineAssociationEntityType(field, attributeType);

                attributes.add(
                        new MendixAttribute(field.getName(), attributeType, associationType, associationEntityType));
            }
            MendixEntity newEntity = new MendixEntity(entityClass.getSimpleName(), attributes);
            mendixEntities.add(newEntity);
        }

        writeToJsonFile(filePath, mendixEntities);
    }
    ...
}

我們首先查找應用程序中標有 JPA 的 @Entity 注釋的所有類。
然后,對于每堂課,我們:

  1. 使用entityClass.getDeclaredFields()獲取聲明的字段。
  2. 循環(huán)該類的每個字段。

對于每個字段,我們:

  1. 確定屬性的類型:

    private static final Map<Class<?>, AttributeType> JAVA_TO_MENDIX_TYPE = Map.ofEntries(
            Map.entry(String.class, AttributeType.STRING),
            Map.entry(Integer.class, AttributeType.INTEGER),
            ...
            );
    // we return AttributeType.ENTITY if we cannot map to anything else
    

    本質(zhì)上,我們只是通過在 JAVA_TO_MENDIX_TYPE 映射中查找 java 類型與我們的自定義枚舉值進行匹配。

  2. 接下來,我們檢查這個屬性是否實際上是一個關(guān)聯(lián)(指向另一個@Entity)。如果是這樣,我們確定關(guān)聯(lián)的類型:一對一、一對多、多對多:

    @Entity
    @Table(name = "CAT")
    class Cat {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        private String name;
        private int age;
        private String color;
    
        @OneToOne
        private Human humanPuppet;
    
        ... constructor ...
        ... getters ...
    }
    
    @Entity
    @Table(name = "HUMAN")
    public class Human {
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        private String name;
    
        ... constructor ...
        ... getters ...
    }
    

    為此,我們只需檢查之前映射的屬性類型。如果它是 Entity,這僅意味著在之前的步驟中我們無法將其映射到任何原始 java 類型、String 或 Enum。
    然后我們還需要決定它是什么類型的關(guān)聯(lián)。檢查很簡單:如果是 List 類型,則它是一對多,否則是一對一(尚未實現(xiàn)“多對多”)。

  3. 然后我們?yōu)檎业降拿總€字段創(chuàng)建一個 MendixAttribute 對象。

完成后,我們只需為實體創(chuàng)建一個 MendixEntity 對象并分配屬性列表。
MendixEntity 和 MendixAttribute 是我們稍后將用來映射到 json 的類:

public class MendixExporter {
    public static void exportEntitiesTo(String filePath) throws IOException {
        AnnotatedTypeScanner typeScanner = new AnnotatedTypeScanner(false, Entity.class);

        Set<Class<?>> entityClasses = typeScanner.findTypes(JavaToMendixApplication.class.getPackageName());
        log.info("Entity classes are: {}", entityClasses);

        List<MendixEntity> mendixEntities = new ArrayList<>();

        for (Class<?> entityClass : entityClasses) {
            List<MendixAttribute> attributes = new ArrayList<>();
            for (Field field : entityClass.getDeclaredFields()) {

                AttributeType attributeType = determineAttributeType(field);
                AssociationType associationType = determineAssociationType(field, attributeType);
                String associationEntityType = determineAssociationEntityType(field, attributeType);

                attributes.add(
                        new MendixAttribute(field.getName(), attributeType, associationType, associationEntityType));
            }
            MendixEntity newEntity = new MendixEntity(entityClass.getSimpleName(), attributes);
            mendixEntities.add(newEntity);
        }

        writeToJsonFile(filePath, mendixEntities);
    }
    ...
}

最后,我們保存一個List;使用 Jackson 轉(zhuǎn)換為 json 文件。

將實體導入 Mendix

有趣的部分來了,我們?nèi)绾巫x取上面生成的 json 文件并從中創(chuàng)建 mendix 實體?

Mendix 的 Platform SDK 有一個 Typescript API 可以與之交互。
首先,我們將創(chuàng)建對象來表示我們的實體和屬性,以及關(guān)聯(lián)和屬性類型的枚舉:

private static final Map<Class<?>, AttributeType> JAVA_TO_MENDIX_TYPE = Map.ofEntries(
        Map.entry(String.class, AttributeType.STRING),
        Map.entry(Integer.class, AttributeType.INTEGER),
        ...
        );
// we return AttributeType.ENTITY if we cannot map to anything else

接下來,我們需要使用 appId 獲取我們的應用程序,創(chuàng)建臨時工作副本,打開模型,并找到我們感興趣的域模型:

private static AssociationType determineAssociationType(Field field, AttributeType attributeType) {
    if (!attributeType.equals(AttributeType.ENTITY))
        return null;
    if (field.getType().equals(List.class)) {
        return AssociationType.ONE_TO_MANY;
    } else {
        return AssociationType.ONE_TO_ONE;
    }
}

SDK 實際上會從 git 中提取我們的 mendix 應用程序并進行處理。

讀取 json 文件后,我們將循環(huán)實體:

public record MendixEntity(
        String name,
        List<MendixAttribute> attributes) {
}

public record MendixAttribute(
        String name,
        AttributeType type,
        AssociationType associationType,
        String entityType) {

    public enum AttributeType {
        STRING,
        INTEGER,
        DECIMAL,
        AUTO_NUMBER,
        BOOLEAN,
        ENUM,
        ENTITY;
    }

    public enum AssociationType {
        ONE_TO_ONE,
        ONE_TO_MANY
    }
}

這里我們使用domainmodels.Entity.createIn(domainModel);在我們的域模型中創(chuàng)建一個新實體并為其分配一個名稱。我們可以分配更多屬性,例如文檔、索引,甚至實體在域模型中呈現(xiàn)的位置。

我們在單獨的函數(shù)中處理屬性:

interface ImportedEntity {
    name: string;
    generalization: string;
    attributes: ImportedAttribute[];
}

interface ImportedAttribute {
    name: string;
    type: ImportedAttributeType;
    entityType: string;
    associationType: ImportedAssociationType;
}

enum ImportedAssociationType {
    ONE_TO_ONE = "ONE_TO_ONE",
    ONE_TO_MANY = "ONE_TO_MANY"
}

enum ImportedAttributeType {
    INTEGER = "INTEGER",
    STRING = "STRING",
    DECIMAL = "DECIMAL",
    AUTO_NUMBER = "AUTO_NUMBER",
    BOOLEAN = "BOOLEAN",
    ENUM = "ENUM",
    ENTITY = "ENTITY"
}

這里我們唯一需要付出一些努力的就是將屬性類型映射到有效的 mendix 類型。

接下來我們處理關(guān)聯(lián)。首先,由于在我們的Java實體中關(guān)聯(lián)是通過字段聲明的,因此我們需要區(qū)分哪些字段是簡單屬性,哪些字段是關(guān)聯(lián)。為此,我們只需要檢查它是實體類型還是原始類型:

const client = new MendixPlatformClient();
const app = await client.getApp(appId);
const workingCopy = await app.createTemporaryWorkingCopy("main");
const model = await workingCopy.openModel();
const domainModelInterface = model.allDomainModels().filter(dm => dm.containerAsModule.name === MyFirstModule")[0];
const domainModel = await domainModelInterface.load();

讓我們創(chuàng)建關(guān)聯(lián):

function createMendixEntities(domainModel: domainmodels.DomainModel, entitiesInJson: any) {
    const importedEntities: ImportedEntity[] = JSON.parse(entitiesInJson);

    importedEntities.forEach((importedEntity, i) => {
        const mendixEntity = domainmodels.Entity.createIn(domainModel);
        mendixEntity.name = importedEntity.name;

        processAttributes(importedEntity, mendixEntity);
    });

    importedEntities.forEach(importedEntity => {
        const mendixParentEntity = domainModel.entities.find(e => e.name === importedEntity.name) as domainmodels.Entity;
        processAssociations(importedEntity, domainModel, mendixParentEntity);
    });
}

除了名稱之外,我們還有 4 個重要的屬性需要設(shè)置:

  1. 父實體。這是當前實體。
  2. 子實體。在最后一步中,我們?yōu)槊總€ java 實體創(chuàng)建了 mendix 實體?,F(xiàn)在我們只需要根據(jù)實體中java字段的類型找到匹配的實體:

    function processAttributes(importedEntity: ImportedEntity, mendixEntity: domainmodels.Entity) {
        importedEntity.attributes.filter(a => a.type !== ImportedAttributeType.ENTITY).forEach(a => {
            const mendixAttribute = domainmodels.Attribute.createIn(mendixEntity);
            mendixAttribute.name = capitalize(getAttributeName(a.name, importedEntity));
            mendixAttribute.type = assignAttributeType(a.type, mendixAttribute);
        });
    }
    
  3. 關(guān)聯(lián)類型。如果是一對一的,它會映射到一個引用。如果是一對多,則映射到參考集。我們現(xiàn)在將跳過多對多。

  4. 協(xié)會所有者。一對一和多對多關(guān)聯(lián)都具有相同的所有者類型:兩者。對于一對一,所有者類型必須為默認。

Mendix Platform SDK 將在我們的 mendix 應用程序的本地工作副本中創(chuàng)建實體?,F(xiàn)在我們只需要告訴它提交更改:

@Entity
@Table(name = "CAT")
class Cat {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private int age;
    private String color;

    @OneToOne
    private Human humanPuppet;

    ... constructor ...
    ... getters ...
}

@Entity
@Table(name = "HUMAN")
public class Human {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    ... constructor ...
    ... getters ...
}

幾秒鐘后,您可以在 Mendix Studio Pro 中打開應用程序并驗證結(jié)果:
Converting JPA entities to Mendix

現(xiàn)在你已經(jīng)看到了:貓和人的實體,它們之間存在一對一的關(guān)聯(lián)。

如果您想親自嘗試或查看完整代碼,請訪問此存儲庫。

對未來的想法

  1. 在這個示例中,我使用了 Java/Spring 應用程序進行轉(zhuǎn)換,因為我最精通它,但任何應用程序都可以使用。 只需能夠讀取類型數(shù)據(jù)(靜態(tài)或運行時)來提取類和字段名稱就足夠了。
  2. 我很好奇嘗試讀取一些 Java 邏輯并將其導出到 Mendix 微流程。我們可能無法真正轉(zhuǎn)換業(yè)務邏輯本身,但我們應該能夠獲得它的結(jié)構(gòu)(至少是業(yè)務方法簽名?)。
  3. 本文中的代碼可以推廣并制作成一個庫:json 格式可以保持不變,并且可以有一個庫用于導出 java 類型,另一個庫用于導入 mendix 實體。
  4. 我們可以使用相同的方法進行相反的操作:將 mendix 轉(zhuǎn)換為另一種語言。

結(jié)論

Mendix Platform SDK 是一項強大的功能,允許以編程方式與 mendix 應用程序進行交互。他們列出了一些示例用例,例如導入/導出代碼、分析應用程序復雜性。
如果您有興趣,請看一下。
對于本文,您可以在此處找到完整代碼。

以上是將 JPA 實體轉(zhuǎn)換為 Mendix的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔相應法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

hashmap和hashtable之間的區(qū)別? hashmap和hashtable之間的區(qū)別? Jun 24, 2025 pm 09:41 PM

HashMap與Hashtable的區(qū)別主要體現(xiàn)在線程安全、null值支持及性能方面。1.線程安全方面,Hashtable是線程安全的,其方法大多為同步方法,而HashMap不做同步處理,非線程安全;2.null值支持上,HashMap允許一個null鍵和多個null值,Hashtable則不允許null鍵或值,否則拋出NullPointerException;3.性能方面,HashMap因無同步機制效率更高,Hashtable因每次操作加鎖性能較低,推薦使用ConcurrentHashMap替

為什么我們需要包裝紙課? 為什么我們需要包裝紙課? Jun 28, 2025 am 01:01 AM

Java使用包裝類是因為基本數(shù)據(jù)類型無法直接參與面向?qū)ο蟛僮?,而實際需求中常需對象形式;1.集合類只能存儲對象,如List利用自動裝箱存儲數(shù)值;2.泛型不支持基本類型,必須使用包裝類作為類型參數(shù);3.包裝類可表示null值,用于區(qū)分未設(shè)置或缺失的數(shù)據(jù);4.包裝類提供字符串轉(zhuǎn)換等實用方法,便于數(shù)據(jù)解析與處理,因此在需要這些特性的場景下,包裝類不可或缺。

什么是接口中的靜態(tài)方法? 什么是接口中的靜態(tài)方法? Jun 24, 2025 pm 10:57 PM

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

JIT編譯器如何優(yōu)化代碼? JIT編譯器如何優(yōu)化代碼? Jun 24, 2025 pm 10:45 PM

JIT編譯器通過方法內(nèi)聯(lián)、熱點檢測與編譯、類型推測與去虛擬化、冗余操作消除四種方式優(yōu)化代碼。1.方法內(nèi)聯(lián)減少調(diào)用開銷,將頻繁調(diào)用的小方法直接插入調(diào)用處;2.熱點檢測識別高頻執(zhí)行代碼并集中優(yōu)化,節(jié)省資源;3.類型推測收集運行時類型信息實現(xiàn)去虛擬化調(diào)用,提升效率;4.冗余操作消除根據(jù)運行數(shù)據(jù)刪除無用計算和檢查,增強性能。

什么是實例初始器塊? 什么是實例初始器塊? Jun 25, 2025 pm 12:21 PM

實例初始化塊在Java中用于在創(chuàng)建對象時運行初始化邏輯,其執(zhí)行先于構(gòu)造函數(shù)。它適用于多個構(gòu)造函數(shù)共享初始化代碼、復雜字段初始化或匿名類初始化場景,與靜態(tài)初始化塊不同的是它每次實例化時都會執(zhí)行,而靜態(tài)初始化塊僅在類加載時運行一次。

什么是工廠模式? 什么是工廠模式? Jun 24, 2025 pm 11:29 PM

工廠模式用于封裝對象創(chuàng)建邏輯,使代碼更靈活、易維護、松耦合。其核心答案是:通過集中管理對象創(chuàng)建邏輯,隱藏實現(xiàn)細節(jié),支持多種相關(guān)對象的創(chuàng)建。具體描述如下:工廠模式將對象創(chuàng)建交給專門的工廠類或方法處理,避免直接使用newClass();適用于多類型相關(guān)對象創(chuàng)建、創(chuàng)建邏輯可能變化、需隱藏實現(xiàn)細節(jié)的場景;例如支付處理器中通過工廠統(tǒng)一創(chuàng)建Stripe、PayPal等實例;其實現(xiàn)包括工廠類根據(jù)輸入?yún)?shù)決定返回的對象,所有對象實現(xiàn)共同接口;常見變體有簡單工廠、工廠方法和抽象工廠,分別適用于不同復雜度的需求。

變量的最終關(guān)鍵字是什么? 變量的最終關(guān)鍵字是什么? Jun 24, 2025 pm 07:29 PM

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

什么是類型鑄造? 什么是類型鑄造? Jun 24, 2025 pm 11:09 PM

類型轉(zhuǎn)換有兩種:隱式和顯式。1.隱式轉(zhuǎn)換自動發(fā)生,如將int轉(zhuǎn)為double;2.顯式轉(zhuǎn)換需手動操作,如使用(int)myDouble。需要類型轉(zhuǎn)換的情況包括處理用戶輸入、數(shù)學運算或函數(shù)間傳遞不同類型的值時。需要注意的問題有:浮點數(shù)轉(zhuǎn)整數(shù)會截斷小數(shù)部分、大類型轉(zhuǎn)小類型可能導致數(shù)據(jù)丟失、某些語言不允許直接轉(zhuǎn)換特定類型。正確理解語言的轉(zhuǎn)換規(guī)則有助于避免錯誤。

See all articles