基于POSTGRESQL的全局序列操作
使用全局序列生成器,在业务中标记区分,比如信令的区分!
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
/**
* @ClassName SequenceMapper
* @Description sql序列操作
* @Author zhaoyj
* @Date 2019/4/30 12:45
*/
public interface SequenceMapper {
String name = "mytable_myid_seq";
@Select("SELECT nextval('"+ name + "')")
Integer nextIntegerId();
@Delete("DROP SEQUENCE IF EXISTS " + name)
void delete();
@Insert("CREATE SEQUENCE " + name + " INCREMENT 1 START 1 MINVALUE 1 MAXVALUE " + Integer.MAX_VALUE +" CACHE 1;")
void create();
@Select("select relname from pg_class where relkind='S' and relname='" + name + "'")
String find();
}
全局获取序列
可以创建一个单例类型的类,获取序列,如下:
import com.mti.mapper.SequenceMapper;
import org.springframework.util.StringUtils;
/**
* @ClassName SecUtils
* @Description SecUtils
* @Author zhaoyj
* @Date 2019/4/29 11:47
*/
public class SecUtils {
private static SequenceMapper mapper;
/**
* 获取下一个序列
* @return
*/
public static Integer nextIntegerId(){
if(mapper == null){
synchronized (SecUtils.class){
if(mapper == null){
init();
}
}
}
return mapper.nextIntegerId();
}
/**
* 初始化序列
*/
private static void init(){
mapper = SpringUtils.getBean(SequenceMapper.class);
if(StringUtils.isEmpty(mapper.find())){
mapper.create();
}
}
}