Mybatis Plus obtains the column name corresponding to the database through lambda

Project scenario:

Mybatis Plus通过lambda获取数据库对应的列名


solution:

Obtain the column name corresponding to the database through the LambdaUtils tool class that comes with baomidou

1. Introduce maven dependency

<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>5.8.0</version>
</dependency>

<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.5.1</version>
</dependency>

2. Create entities

@Data
@TableName("test")
public class TestEntity {

    @ApiModelProperty(value = "主键id")
	@TableId
    private String id;

    @ApiModelProperty(value = "完整姓名")
    @TableField("pull_name")
    private String pullName;
}

3. Test

import cn.hutool.core.lang.func.LambdaUtil;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.ColumnCache;
import org.junit.Test;

@Test
public void test() {
    //获取实体所有对应的列
	Map<String, ColumnCache> testMap = LambdaUtils.getColumnMap(TestEntity.class);
    //hutool包,获取实体属性名称
	String fieldName = LambdaUtil.getFieldName(TestEntity::getPullName);
    //通过属性名获取对应的列名
    String column = testMap.get(LambdaUtils.formatKey(fieldName)).getColumn();
    System.out.println(column);
}


If you don't want to refer to the hutool package here, you can write a method to get the attribute name

package test;

import java.beans.Introspector;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.function.Function;
 
 
@FunctionalInterface
public interface TypeFunction<T, R> extends Serializable, Function<T, R> {
 
    /**
     * 获取列名称
     * @param lambda
     * @return String
     */
    static String getLambdaColumnName(Serializable lambda) {
        try {
            Method method = lambda.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            SerializedLambda serializedLambda = (SerializedLambda) method.invoke(lambda);
            String getter = serializedLambda.getImplMethodName();
            String fieldName = Introspector.decapitalize(getter.replace("get", ""));
            return fieldName;
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }
    
    static <T, R> String getFieldName(TypeFunction<T, R> name){
    	return getLambdaColumnName(name);
    }
}

Test, changed the way to get the attribute name

@Test
public void test() {
    //获取实体所有对应的列
	Map<String, ColumnCache> testMap = LambdaUtils.getColumnMap(TestEntity.class);
    //自定义方法,获取实体属性名称
	String fieldName = TypeFunction.getFieldName(TestEntity::getPullName);
    //通过属性名获取对应的列名
    String column = testMap.get(LambdaUtils.formatKey(fieldName)).getColumn();
    System.out.println(column);
}

Guess you like

Origin blog.csdn.net/u011974797/article/details/130616631