NutzCN Logo
分享 beetlsql兼容nutzdao注解
发布于 1831天前 作者 WenTao-Love 1938 次浏览 复制 上一个帖子 下一个帖子
标签:
package com.ibeetl.ext;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.beetl.sql.core.NameConversion;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.lang.Strings;

import cn.hutool.core.util.StrUtil;

public class NutzDaoNameConversion extends  NameConversion{

	private static final Map<Class<?>, Map<String, String>> PROP2COL_CACHE = new ConcurrentHashMap<>();
	private static final Map<Class<?>, Map<String, String>> COL2PROP_CACHE = new ConcurrentHashMap<>();
	private static final Map<Class<?>, String> TABLE_CACHE = new ConcurrentHashMap<>();
	
	
	@Override
	public String getTableName(Class<?> c) {
		String tableName = TABLE_CACHE.get(c);
		if(StrUtil.isBlank(tableName)) {
			Table table = c.getAnnotation(Table.class);
			tableName = table.prefix()+table.value()+table.suffix();
			TABLE_CACHE.put(c, tableName);
		}
		return tableName;
	}

	@Override
	public String getColName(Class<?> c, String attrName) {
		init(c);
        return PROP2COL_CACHE.get(c).get(attrName);
	}

	@Override
	public String getPropertyName(Class<?> c, String colName) {
		init(c);
        return COL2PROP_CACHE.get(c).get(colName);
	}

	private void init(Class<?> c) {
		if(COL2PROP_CACHE.containsKey(c) && PROP2COL_CACHE.containsKey(c)) return;
		Field[] fields = c.getDeclaredFields();
		Map<String, String> cols = PROP2COL_CACHE.get(c);
        Map<String, String> props = COL2PROP_CACHE.get(c);
        if(cols == null){
            cols = new ConcurrentHashMap<>();
            for (Field field : fields) {
                Column column = field.getAnnotation(Column.class);
                if (column != null) {
                	boolean hump = column.hump();
                	String fieldName = field.getName();
                	if(hump) {
                		cols.put(fieldName, Strings.lowerWord(fieldName, '_'));
                	}else {
                		cols.put(fieldName, column.prefix()+column.value()+column.suffix());                		
                	}
                }
            }
            PROP2COL_CACHE.put(c, cols);
        }
        if(props == null){
            props = new ConcurrentHashMap<>();
            for (Field field : fields) {
                Column column = field.getAnnotation(Column.class);
                if (column != null) {
                	boolean hump = column.hump();
                	String fieldName = field.getName();
                	if(hump) {
                		props.put(Strings.lowerWord(fieldName, '_'), fieldName);
                	}else {
                		props.put(column.prefix()+column.value()+column.suffix(), fieldName);                		
                	}
                }
            }
            COL2PROP_CACHE.put(c, props);
        }
	}
	
}

0 回复
添加回复
请先登陆
回到顶部