将 JPA 实体转换为 Mendix

wufei123 2025-01-26 阅读:12 评论:0
最近在探索 mendix 时,我注意到他们有一个 platform sdk,允许您通过 api 与 mendix 应用程序模型进行交互。 这给了我一个想法,探索它是否可以用于创建我们的领域模型。具体来说,是基于现有的传统应用程序创建领域模...

最近在探索 mendix 时,我注意到他们有一个 platform sdk,允许您通过 api 与 mendix 应用程序模型进行交互。

这给了我一个想法,探索它是否可以用于创建我们的领域模型。具体来说,是基于现有的传统应用程序创建领域模型。

如果进一步推广,这可用于将任何现有应用程序转换为 mendix 并从那里继续开发。

将 java/spring web 应用程序转换为 mendix

因此,我创建了一个带有简单 api 和数据库层的小型 java/spring web 应用程序。为了简单起见,它使用嵌入式 h2 数据库。

在这篇文章中,我们将仅转换 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 ...
}

如您所见,它们非常简单:一只有名字、年龄、颜色的猫和它的人类傀儡,因为正如我们所知,猫统治着世界。

它们都有一个自动生成的 id 字段。猫与人类有一对一的联系,这样它就可以随时呼唤人类。 (如果它不是 jpa 实体,我会放置一个 meow() 方法,但让我们将其留到将来)。

应用程序功能齐全,但现在我们只对数据层感兴趣。

提取 json 中的实体元数据

这可以通过几种不同的方式来完成:

  1. 通过静态分析包中的实体。
  2. 通过使用反射在运行时读取这些实体。

我选择了选项 2,因为它更快,而且我无法轻松找到可以执行选项 1 的库。

接下来,我们需要决定构建后如何公开 json。为了简单起见,我们只需将其写入文件即可。一些替代方法可能是:

  • 通过 api 公开它。这更加复杂,因为您还需要确保端点受到很好的保护,因为我们不能公开暴露我们的元数据。
  • 通过一些管理工具公开它,例如 spring boot actuator 或 jmx。它更安全,但仍然需要时间来设置。

现在让我们看看实际的代码:

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. 循环该类的每个字段。

对于每个字段,我们:

  1. 确定属性的类型:

    private static final map<class>, attributetype&gt; 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
    </class>

    本质上,我们只是通过在 java_to_mendix_type 映射中查找 java 类型与我们的自定义枚举值进行匹配。

  2. 接下来,我们检查这个属性是否实际上是一个关联(指向另一个@entity)。如果是这样,我们确定关联的类型:一对一、一对多、多对多:

    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;
        }
    }
    

    为此,我们只需检查之前映射的属性类型。如果它是 entity,这仅意味着在之前的步骤中我们无法将其映射到任何原始 java 类型、string 或 enum。
    然后我们还需要决定它是什么类型的关联。检查很简单:如果是 list 类型,则它是一对多,否则是一对一(尚未实现“多对多”)。

  3. 然后我们为找到的每个字段创建一个 mendixattribute 对象。

完成后,我们只需为实体创建一个 mendixentity 对象并分配属性列表。
mendixentity 和 mendixattribute 是我们稍后将用来映射到 json 的类:

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
    }
}

最后,我们使用 jackson 将 list 保存到 json 文件中。

将实体导入 mendix

有趣的部分来了,我们如何读取上面生成的 json 文件并从中创建 mendix 实体?

mendix 的 platform sdk 有一个 typescript api 可以与之交互。
首先,我们将创建对象来表示我们的实体和属性,以及关联和属性类型的枚举:

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"
}

接下来,我们需要使用 appid 获取我们的应用程序,创建临时工作副本,打开模型,并找到我们感兴趣的域模型:

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();

sdk 实际上会从 git 中提取我们的 mendix 应用程序并进行处理。

读取 json 文件后,我们将循环实体:

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);
    });
}

这里我们使用domainmodels.entity.createin(domainmodel);在我们的域模型中创建一个新实体并为其分配一个名称。我们可以分配更多属性,例如文档、索引,甚至实体在域模型中呈现的位置。

我们在单独的函数中处理属性:

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);
    });
}

这里我们唯一需要付出一些努力的就是将属性类型映射到有效的 mendix 类型。

接下来我们处理关联。首先,由于在我们的java实体中关联是通过字段声明的,因此我们需要区分哪些字段是简单属性,哪些字段是关联。为此,我们只需要检查它是实体类型还是原始类型:

importedentity.attributes.filter(a => a.type === importedattributetype.entity) ...

让我们创建关联:

const mendixassociation = domainmodels.association.createin(domainmodel);

const mendixchildentity = domainmodel.entities.find(e =&gt; e.name === a.entitytype) as domainmodelsentity;
mendixassociation.name = `${mendixparententity?.name}_${mendixchildentity?.name}`;
mendixassociation.parent = mendixparententity;
mendixassociation.child = mendixchildentity;

mendixassociation.type = a.associationtype === importedassociationtype.one_to_one || a.associationtype === importedassociationtype.one_to_many ?
    domainmodels.associationtype.reference : domainmodels.associationtype.referenceset;
mendixassocation.owner = a.associationtype === importedassociationtype.one_to_one ? domainmodelsassociationowner.both : domainmodels.associationowner.default;

除了名称之外,我们还有 4 个重要的属性需要设置:

  1. 父实体。这是当前实体。
  2. 子实体。在最后一步中,我们为每个 java 实体创建了 mendix 实体。现在我们只需要根据实体中java字段的类型找到匹配的实体:

    domainmodel.entities.find(e =&gt; e.name === a.entitytype) as domainmodelsentity;
    
  3. 关联类型。如果是一对一的,它会映射到一个引用。如果是一对多,则映射到参考集。我们现在将跳过多对多。

  4. 协会所有者。一对一和多对多关联都具有相同的所有者类型:两者。对于一对一,所有者类型必须为默认。

mendix platform sdk 将在我们的 mendix 应用程序的本地工作副本中创建实体。现在我们只需要告诉它提交更改:

async function commitChanges(model: IModel, workingCopy: OnlineWorkingCopy, entitiesFile: string) {
    await model.flushChanges();
    await workingCopy.commitToRepository("main", { commitMessage: `Imported DB entities from ${entitiesFile}` });
}

几秒钟后,您可以在 mendix studio pro 中打开应用程序并验证结果:
generated mendix domain model

现在你已经看到了:猫和人的实体,它们之间存在一对一的关联。

如果您想亲自尝试或查看完整代码,请访问此存储库。

对未来的想法
  1. 在这个示例中,我使用了 java/spring 应用程序进行转换,因为我最精通它,但任何应用程序都可以使用。 只需能够读取类型数据(静态或运行时)来提取类和字段名称就足够了。
  2. 我很好奇尝试读取一些 java 逻辑并将其导出到 mendix 微流程。我们可能无法真正转换业务逻辑本身,但我们应该能够获得它的结构(至少是业务方法签名?)。
  3. 本文中的代码可以推广并制作成一个库:json 格式可以保持不变,并且可以有一个库用于导出 java 类型,另一个库用于导入 mendix 实体。
  4. 我们可以使用相同的方法进行相反的操作:将 mendix 转换为另一种语言。
结论

mendix platform sdk 是一项强大的功能,允许以编程方式与 mendix 应用程序进行交互。他们列出了一些示例用例,例如导入/导出代码、分析应用程序复杂性。
如果您有兴趣,请看一下。
对于本文,您可以在此处找到完整代码。

以上就是将 JPA 实体转换为 Mendix的详细内容,更多请关注知识资源分享宝库其它相关文章!

版权声明

本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com

分享:

扫一扫在手机阅读、分享本文

发表评论
热门文章
  • 闪耀暖暖靡城永恒怎么样-闪耀暖暖靡城永恒套装介绍(闪耀.暖暖.套装.介绍.....)

    闪耀暖暖靡城永恒怎么样-闪耀暖暖靡城永恒套装介绍(闪耀.暖暖.套装.介绍.....)
    闪耀暖暖钻石竞技场第十七赛季“华梦泡影”即将开启!全新闪耀性感套装【靡城永恒】震撼来袭!想知道如何获得这套精美套装吗?快来看看吧! 【靡城永恒】套装设计理念抢先看: 设计灵感源于夜色中的孤星,象征着淡然、漠视一切的灰色瞳眸。设计师希望通过这套服装,展现出在虚幻与真实交织的夜幕下,一种独特的魅力。 服装细节考究,从面料的光泽、鞋跟声响到裙摆的弧度,都力求完美还原设计初衷。 【靡城永恒】套装设计亮点: 闪耀的绸缎与金丝交织,轻盈的羽毛增添华贵感。 这套服装仿佛是从无尽的黑...
  • BioWare埃德蒙顿工作室面临关闭危机,龙腾世纪制作总监辞职引关注(龙腾.总监.辞职.危机.面临.....)

    BioWare埃德蒙顿工作室面临关闭危机,龙腾世纪制作总监辞职引关注(龙腾.总监.辞职.危机.面临.....)
    知名变性人制作总监corrine busche离职bioware,引发业界震荡!外媒“smash jt”独家报道称,《龙腾世纪:影幢守护者》制作总监corrine busche已离开bioware,此举不仅引发了关于个人职业发展方向的讨论,更因其可能预示着bioware埃德蒙顿工作室即将关闭而备受关注。本文将深入分析busche离职的原因及其对bioware及游戏行业的影响。 Busche的告别信:挑战与感激并存 据“Smash JT”获得的内部邮件显示,Busche离职原...
  • 奇迹暖暖诸星梦眠怎么样-奇迹暖暖诸星梦眠套装介绍(星梦.暖暖.奇迹.套装.介绍.....)

    奇迹暖暖诸星梦眠怎么样-奇迹暖暖诸星梦眠套装介绍(星梦.暖暖.奇迹.套装.介绍.....)
    奇迹暖暖全新活动“失序之圜”即将开启,参与活动即可获得精美套装——诸星梦眠!想知道这套套装的细节吗?一起来看看吧! 奇迹暖暖诸星梦眠套装详解 “失序之圜”活动主打套装——诸星梦眠,高清海报震撼公开!少女在无垠梦境中,接受星辰的邀请,馥郁芬芳,预示着命运之花即将绽放。 诸星梦眠套装包含:全新妆容“隽永之梦”、星光面饰“熠烁星光”、动态特姿连衣裙“诸星梦眠”、动态特姿发型“金色绮想”、精美特效皇冠“繁星加冕”,以及动态摆件“芳馨酣眠”、“沉云余音”、“流星低语”、“葳蕤诗篇”。...
  • 斗魔骑士哪个角色强势-斗魔骑士角色推荐与实力解析(骑士.角色.强势.解析.实力.....)

    斗魔骑士哪个角色强势-斗魔骑士角色推荐与实力解析(骑士.角色.强势.解析.实力.....)
    斗魔骑士角色选择及战斗策略指南 斗魔骑士游戏中,众多角色各具特色,选择适合自己的角色才能在战斗中占据优势。本文将为您详细解读如何选择强力角色,并提供团队协作及角色培养策略。 如何选择强力角色? 斗魔骑士的角色大致分为近战和远程两种类型。近战角色通常拥有高攻击力和防御力,适合冲锋陷阵;远程角色则擅长后方输出,并依靠灵活走位躲避攻击。 选择角色时,需根据个人游戏风格和喜好决定。喜欢正面硬刚的玩家可以选择战士型角色,其高生命值和防御力能承受更多伤害;偏好策略性玩法的玩家则可以选择法...
  • 龙族卡塞尔之门昂热角色详解-龙族卡塞尔之门昂热全面介绍(之门.龙族.卡塞尔.详解.角色.....)

    龙族卡塞尔之门昂热角色详解-龙族卡塞尔之门昂热全面介绍(之门.龙族.卡塞尔.详解.角色.....)
    龙族卡塞尔之门:昂热角色深度解析 在策略手游《龙族卡塞尔之门》中,卡塞尔学院校长昂热凭借其传奇背景和强大技能,成为玩家们竞相选择的热门角色。作为初代狮心会的最后一人,他拥有超过130岁的阅历,沉稳成熟的外表下,藏着一颗爽朗豁达的心。游戏中,昂热不仅具备出色的单体输出,更擅长通过控制和辅助技能,为团队创造优势。 技能机制详解 昂热的技能组合灵活多变,包含普通攻击、言灵·时零以及随星级提升解锁的被动技能。虽然普通攻击仅针对单体目标,但言灵·时零却能对全体敌人造成物理伤害,并有几率...