Java gets the table name of the generic object entity class

 Description:

        Obtaining the entity object table name is mainly to obtain the table name for special business, but to obtain the table name does not have to be obtained in this way, but this is a function implemented for unification, which is actually implemented here, https://blog .csdn.net/qq_38428623/article/details/105234896

1. Entity type

import javax.persistence.Table;

@Data
@Table(name = "Test")
public class Test {
   
    /**
     * 主键
     */
    @Id
    private String id;

    /**
     * 请假人ID
     */
    @Column(name = "name")
    private String name;
}

2. Basic query (core code only) 

/**
* T:实体类
*/
public class BaseQuery<T> {

    /**
     * 获取实体类的表名
     */
    public String getTableName(){
        finalParameterizedType paraType = (ParameterizedType) 
        this.getClass().getGenericSuperclass();
        final Type[] types = paraType.getActualTypeArguments();
        String tableName = null;
        for (final Type type : types) {
            final Annotation annotation = ((Class) type).getAnnotation(Table.class);
            if (annotation == null) {
                continue;
            }
            tableName = ((Table) annotation).name();
            break;
        }
       return tableName;
    }
}

 

Guess you like

Origin blog.csdn.net/qq_38428623/article/details/105423350