项目场景:

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


解决方案:

通过baomidou自带的LambdaUtils工具类获取数据库对应的列名

1.引入maven依赖

<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.创建实体

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

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

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

3.测试

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


这里如果不想引用hutool的包,可以自己写个方法获取属性名

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

更多推荐