不使用修饰符的架构定义

balp4ylt  于 2022-10-22  发布在  Java
关注(0)|答案(1)|浏览(138)

我试图在纯代码中定义模式,而不使用“实验性”修饰符。使用装饰器可以实现的一切都应该在纯代码中实现,不是吗?
下面是一个例子,说明我目前所做的工作,我将在之后提出我的问题:

// define the TypeScript type
export type ProjectRecord = {
    project_id: string

    name: string
    created: Date
}

// instantiate the schema in pure code
export const ProjectSchema = new EntitySchema<ProjectRecord>({
    name: "PROJECT",
    tableName: "project",
    columns: {
        project_id: {primary: true, type: "varchar", length: 32},

        name: {type: "varchar", length: 128},
        created: {type: "datetime"},
    },
});

这对于进行非常原始的CRUD操作非常有效。我没有能够做的是定义模式之间的关系,以便透明地执行JOIN操作。假设上面定义的ProjectSchema和其他地方定义的m2n2o1p(一个用户有多个项目),我如何定义relations配置选项?
我使用TypeScript类型提示对代码进行了修改,并设法在EntitySchema构造函数中获得了以下配置,作为起点,但它非常不完整。

relations: {
    user_id: {
        target: {
            type: UserSchema,
            name: "u"
        },
        type: "one-to-many"
    }
}

理想情况下,我可以只执行:project.useruser.projects来访问链接对象。如果您还可以向我展示级联操作配置的样子(对于级联和非级联情况),我将非常感激。
非常感谢。

4nkexdtk

4nkexdtk1#

目前,我在一些实现过程中遇到了相同的问题。。。
我选择使用纯实体来避免与Typeorm框架耦合。
JavaScript example repository
以下是Typeorm documentation的示例:

应用.js

var typeorm = require("typeorm")

var dataSource = new typeorm.DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "admin",
    database: "test",
    synchronize: true,
    entities: [require("./entity/Post"), require("./entity/Category")],
})

dataSource
    .initialize()
    .then(function () {
        var category1 = {
            name: "TypeScript",
        }
        var category2 = {
            name: "Programming",
        }

        var post = {
            title: "Control flow based type analysis",
            text: "TypeScript 2.0 implements a control flow-based type analysis for local variables and parameters.",
            categories: [category1, category2],
        }

        var postRepository = dataSource.getRepository("Post")
        postRepository
            .save(post)
            .then(function (savedPost) {
                console.log("Post has been saved: ", savedPost)
                console.log("Now lets load all posts: ")

                return postRepository.find()
            })
            .then(function (allPosts) {
                console.log("All posts: ", allPosts)
            })
    })
    .catch(function (error) {
        console.log("Error: ", error)
    })

实体/类别.js

var EntitySchema = require("typeorm").EntitySchema

module.exports = new EntitySchema({
    name: "Category", // Will use table name `category` as default behaviour.
    tableName: "categories", // Optional: Provide `tableName` property to override the default behaviour for table name.
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: true,
        },
        name: {
            type: "varchar",
        },
    },
})

实体/Post.js

var EntitySchema = require("typeorm").EntitySchema

module.exports = new EntitySchema({
    name: "Post", // Will use table name `post` as default behaviour.
    tableName: "posts", // Optional: Provide `tableName` property to override the default behaviour for table name.
    columns: {
        id: {
            primary: true,
            type: "int",
            generated: true,
        },
        title: {
            type: "varchar",
        },
        text: {
            type: "text",
        },
    },
    relations: {
        categories: {
            target: "Category",
            type: "many-to-many",
            joinTable: true,
            cascade: true,
        },
    },
})

关系选项

export interface EntitySchemaRelationOptions {

    /**
     * Indicates with which entity this relation is made.
     */
    target: Function|string;

    /**
     * Type of relation. Can be one of the value of the RelationTypes class.
     */
    type: RelationType;

    /**
     * Inverse side of the relation.
     */
    inverseSide?: string;

    /**
     * Indicates if this relation will be lazily loaded.
     */
    lazy?: boolean;

    /**
     * Indicates if this relation will be eagerly loaded.
     */
    eager?: boolean;

    /**
     * Indicates if persistence is enabled for the relation.
     * By default its enabled, but if you want to avoid any changes in the relation to be reflected in the database you can disable it.
     * If its disabled you can only change a relation from inverse side of a relation or using relation query builder functionality.
     * This is useful for performance optimization since its disabling avoid multiple extra queries during entity save.
     */
    persistence?: boolean;

    /**
     * Indicates if this relation will be a primary key.
     * Can be used only for many-to-one and owner one-to-one relations.
     */
    primary?: boolean;

    /**
     * Join table options of this column. If set to true then it simply means that it has a join table.
     */
    joinTable?: boolean|JoinTableOptions|JoinTableMultipleColumnsOptions;

    /**
     * Join column options of this column. If set to true then it simply means that it has a join column.
     */
    joinColumn?: boolean|JoinColumnOptions;

    /**
     * Indicates if this is a parent (can be only many-to-one relation) relation in the tree tables.
     */
    treeParent?: boolean;

    /**
     * Indicates if this is a children (can be only one-to-many relation) relation in the tree tables.
     */
    treeChildren?: boolean;

    /**
     * If set to true then it means that related object can be allowed to be inserted / updated / removed to the db.
     * This is option a shortcut if you would like to set cascadeInsert, cascadeUpdate and cascadeRemove to true.
     */
    cascade?: boolean|("insert"|"update"|"remove")[];

    /**
     * Default database value.
     */
    default?: any;

    /**
     * Indicates if relation column value can be nullable or not.
     */
    nullable?: boolean;

    /**
     * Database cascade action on delete.
     */
    onDelete?: OnDeleteType;

    /**
     * Database cascade action on update.
     */
    onUpdate?: OnUpdateType;

}

相关问题