最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Generic repository to save different entities - Stack Overflow

programmeradmin0浏览0评论

In my spring boot application I have a notification service. I have 4 or 5 tables where there are user entries. When user requests to change some data in any of these tables, I trigger a notification and when admin approves this change request this needs to be updated in the corresponding table.

What I did was I added original data in one column, data to change in another column, entity class name in 3rd column. Entity primary key in fourth column, status of the request in 5th column.

create table tbl_change_requests
(
    id            uuid not null
        primary key,
    change_data   jsonb,
    decided_at    timestamp(6),
    original_data jsonb,
    request_type  varchar(255)
        constraint tbl_change_requests_request_type_check
            check ((request_type)::text = ANY
                   ((ARRAY ['DATE_CHANGE'::character varying, 'PRIORITY_CHANGE'::character varying, 'ASSIGNEE_CHANGE'::character varying, 'STATUS_CHANGE'::character varying, 'DESCRIPTION_CHANGE'::character varying])::text[])),
    requested_at  timestamp(6),
    status        varchar(255)
        constraint tbl_change_requests_status_check
            check ((status)::text = ANY
                   ((ARRAY ['PENDING'::character varying, 'APPROVED'::character varying, 'REJECTED'::character varying])::text[])),
    task_id       uuid,
    requested_by  uuid
        constraint fkc0g49uvky2f4jwjv9i5ytdavv
            references users,
    target_name   varchar(255)
);

Is there any way to write a generic repository to save any valid entity to the corresponding table? (I have the entity class name in DB and I can find the class and I can also find the table it represents)

    public Class<?> getEntityClassFromEntityName(String entityName) {
        for (EntityType<?> entity : entityManager.getMetamodel().getEntities()) {
            if (entityName.equals(entity.getName())) {
                return entity.getJavaType();
            }
        }

        return null;
    }
   public <T> String getTableName(Class<T> entityClass) {
        if (entityClass == null)
            return null;

        Metamodel meta = entityManager.getMetamodel();
        EntityType<T> entityType = meta.entity(entityClass);


        Table t = entityClass.getAnnotation(Table.class);

        return (t == null)
                ? entityType.getName().toUpperCase()
                : t.name();
    }
    ```
发布评论

评论列表(0)

  1. 暂无评论