package com.muchinfo.mtp3century.utils;

import com.baomidou.mybatisplus.annotation.TableName;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;

@Component
public class SequenceIDGeneratorUtils {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private SqlSessionFactory sqlSessionFactory;

    public Long getGeneratorID(Class<?> c) {
        try {
            SqlSession session = sqlSessionFactory.openSession();
            ResultSet resultSet = session.getConnection().createStatement()
                    .executeQuery("SELECT SEQ_" + c.getAnnotation(TableName.class).value() + ".NEXTVAL AS id FROM dual");
            if (resultSet.next()) {
                // 移动游标到第一行
                return resultSet.getLong("id");
            } else {
                throw new SQLException("No results returned from the query.");
            }
        } catch (Exception e) {
            log.error("No results returned from the query.");
            return null;
        }
    }
}
