Redis获取自增id
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.u
·
记录一份代码
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();
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)