自定义ORM(mybatis)源码(三)-创建SqlSession

自定义ORM(mybatis)源码(三)-创建SqlSession

模仿mybatis

SqlSession

@Slf4j
public class SqlSession {

    @Getter
    private Configuration configuration;

    private Connection connection;

    public SqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    public <T> T getMapper(Class<T> clz) {
        return configuration.getMapper(clz, this);
    }

    /**
     * 获取数据库连接
     *
     * @return
     */
    public Connection getConnection() {
        try {
            this.connection = configuration.getDataSourceFactory().getConnection();
            return this.connection;
        } catch (SQLException e) {
            log.info("could not getConnection from sqlSession");
            throw new RuntimeException(e);
        }
    }

    public void close() {
        if (this.connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                log.info("sqlsession close error", e);
            }
        }
    }
}

SqlSessionFactory

public class SqlSessionFactory {

    private Configuration configuration;

    public SqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    public SqlSession openSession() {
        return new SqlSession(configuration);
    }
}

SqlSessionFactoryBuilder

创建 SqlSessionFactory

public class SqlSessionFactoryBuilder {

    private InputStream inputStream;

    public SqlSessionFactoryBuilder(InputStream inputStream) {
        this.inputStream  = inputStream;
    }
    public SqlSessionFactory build() {
        XmlConfigParser xmlConfigParser = new XmlConfigParser(new Configuration(), this.inputStream);
        return new SqlSessionFactory(xmlConfigParser.parse());
    }
}

你可能感兴趣的:(mybatis,mybatis)