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