0

I have a base entity class BaseDictionary:

@Entity
@Inheritance
public abstract class BaseDictionary {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;

    @Column(name = "code")
    protected String code;

    @Column(name = "is_enabled")
    protected Boolean enabled = true;
}

any child classes

@Entity
@Table(name = DB.DIC_RIGHTS_TYPE, schema = DB.SCHEMA_DIC)
public class DicRightsType extends BaseDictionary {}

@Entity
@Table(name = DB.DIC_ROLES_TYPE, schema = DB.SCHEMA_DIC)
public class DicRolesType extends BaseDictionary {}

There are many child classes like this.

Given an entity class name like DicRightsType I would like to get data from the table associated with the entity of that name. How is it possible to implement?

I wanted to use JPA repositories like this: Using generics in Spring Data JPA repositories but this does not suit my case because I only have the name of the entity class at runtime and do not know how to create a dynamic repository for the class.

Community
  • 1
  • 1
arman.s
  • 3
  • 3

1 Answers1

2

You can write your own JpaRepository implementation to achieve this.

Step 1: A repository registry

class RepositoryRegistrar {
  private static final Map<Class<T>, Repository<T, Serializable>> DICTIONARY = new HashMap<>();

  public static void register(Class<T> entityClass, Repository<T, Serializable> repository) {
    DICTIONARY.put(entityClass, repository);
  }

  public static Repository<T, Serializable> get(Class<T> entityClass) {
    return DICTIONARY.get(entityClass);
  }
}

Step 2: Custom JpaRepository implementation to populate the registry

@NoRepositoryBean
class RegisteringJpaRepository<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> {
  public RegisteringJpaRepository(JpaEntityInformation<T, ?> entityInformation, EntityManager entityManager) {{
    super(entityInformation, entityManager);

    RepositoryRegistrar.register(entityInformation.getJavaType(), this);
  }
}

You will have to tweak the configuration to use your custom implementation. Details for this are provided in the Spring Data JPA documentation.

Step 3: Obtain repository references from the registrar

Repository<?, ?> getRepository(String entityClassName) {
  return RepositoryRegistrar.get(Class.forName(entityClassName));
}
manish
  • 19,695
  • 5
  • 67
  • 91