简体   繁体   中英

Jooq - generic fetching to subtypes

I'm woring on a project where I need to implement inheritance in in a relational DB. I'm forced to build it based on one table. Suppose I have A, B and C types, constructors A(TypeEnum type), B(String bProp), C(String cProp), B and C are subtypes of A and table A has columns ID, TYPE, A_PROP, B_PROP. Can I fetch into a list of subtype of A and take only a specific fields to create a Object like in follow method?

List<? extends A> findAll(Class<? extends A> clazz) {
    return dsl.selectFrom(A)
        .where(A.TYPE.eq(clazz.getSimpleName()))
        .fetchInto(clazz);} 

Sure. With a bit more verbosity:

public <T extends A> List<T> findAll(Class<T> clazz) {
    Table<?> table;

    if (clazz == B.class)
        table = B_TABLE;
    else if (clazz == C.class)
        table = C_TABLE;
    else
        throw new IllegalArgumentException("Class not supported: " + clazz);

    return dsl.selectFrom(table)
              // For convenience, we can use just any table's TYPE column to get type
              // safety. Of course, you could abstract over the TYPE column, too...
              .where(table.field(B_TABLE.TYPE).eq(clazz.getSimpleName()))
              .fetchInto(clazz);
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM