记录一份代码

import java.util.HashMap;
import java.util.Map;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.redis.Redis;

import huazhan.user.vo.User;
import redis.clients.jedis.Jedis;

public class PrimaryKeyGeneratorKit {
    
    /**
     * 需要自增的主键Map
     * key: 表名
     * value: 主键字段名
     */
    private static Map<String, String> primaryKeyMap = new HashMap<>();
    
    static {
        primaryKeyMap.put(User.TABLE_NAME, User.PRIMARY_KEY);
    }
    
    private PrimaryKeyGeneratorKit() {
        throw new IllegalStateException("Utility class");
    }
    
    /** 
     * @Title getIncr 
     * @Description 获取自增id 
     * @param tableName 自增id所属的表名
     * @return Long
     * @version V1.0
     * @date 2021年6月9日 下午5:38:47  
     * @author WuMing
     */
    public static synchronized Long getIncr(String tableName){
        Jedis jedis = Redis.use().getJedis();
        try {
            if(!primaryKeyMap.containsKey(tableName)) {
                throw new ActiveRecordException("idFieldMap中不存在【" + tableName + "】,如需要使用自增id,请先将需要获取自动id的表名添加到 idFieldMap中");
            }
            if(!jedis.exists(tableName)) {
                Number id = Db.queryNumber("SELECT "+ primaryKeyMap.get(tableName) +" FROM "+ tableName +" ORDER BY "+ primaryKeyMap.get(tableName) +" DESC LIMIT 1 ");
                jedis.set(tableName, id == null ? "0" : id.toString());
            }
            return jedis.incr(tableName);
        } finally {
            jedis.close();
        }
    }
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐