0

0

将 JPA 实体转换为 Mendix

心靈之曲

心靈之曲

发布时间:2025-01-13 18:25:55

|

368人浏览过

|

来源于dev.to

转载

最近在探索 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> 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
    

    本质上,我们只是通过在 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<mendixentity> 保存到 json 文件中。

将实体导入 mendix

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

腾讯交互翻译
腾讯交互翻译

腾讯AI Lab发布的一款AI辅助翻译产品

下载

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 => 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 => 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 应用程序进行交互。他们列出了一些示例用例,例如导入/导出代码、分析应用程序复杂性。
如果您有兴趣,请看一下。
对于本文,您可以在此处找到完整代码。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
TypeScript工程化开发与Vite构建优化实践
TypeScript工程化开发与Vite构建优化实践

本专题面向前端开发者,深入讲解 TypeScript 类型系统与大型项目结构设计方法,并结合 Vite 构建工具优化前端工程化流程。内容包括模块化设计、类型声明管理、代码分割、热更新原理以及构建性能调优。通过完整项目示例,帮助开发者提升代码可维护性与开发效率。

47

2026.02.13

TypeScript全栈项目架构与接口规范设计
TypeScript全栈项目架构与接口规范设计

本专题面向全栈开发者,系统讲解基于 TypeScript 构建前后端统一技术栈的工程化实践。内容涵盖项目分层设计、接口协议规范、类型共享机制、错误码体系设计、接口自动化生成与文档维护方案。通过完整项目示例,帮助开发者构建结构清晰、类型安全、易维护的现代全栈应用架构。

194

2026.02.25

spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

160

2025.08.06

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

88

2026.01.26

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

139

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

408

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

73

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

150

2025.12.22

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

76

2026.03.11

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 4.2万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.6万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 94人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号