主頁 > 後端開發 > MyBatis詳細原始碼決議(中篇)

MyBatis詳細原始碼決議(中篇)

2020-12-15 12:37:55 後端開發

XMLStatementBuilder類中的parseStatementNode方法是真正開始決議指定的SQL節點,

從上文中可知context就是SQL標簽對應的XNode物件,該方法前面大部分內容都是從XNode物件中獲取各個資料,其實該方法的大致意思就是決議這個SQL標簽里的所有資料(SQL陳述句以及標簽屬性),并把所有資料通過addMappedStatement這個方法封裝在MappedStatement這個物件中,這個物件中封裝了一條SQL所在標簽的所有內容,比如這個SQL標簽的id、SQL陳述句、輸入值、輸出值等,我們要清楚一個SQL的標簽就對應一個MappedStatement物件,

public void parseStatementNode() {
    // 通過XNode物件獲取標簽的各個資料
    String id = context.getStringAttribute("id");
    String databaseId = context.getStringAttribute("databaseId");
    if (!databaseIdMatchesCurrent(id, databaseId, this.requiredDatabaseId)) {
        return;
    }
    String nodeName = context.getNode().getNodeName();
	
    // 省略其他內容...
    
    // 獲取SQL陳述句并封裝成一個SqlSource物件
    SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);
    String keyColumn = context.getStringAttribute("keyColumn");
    String resultSets = context.getStringAttribute("resultSets");

    // 將SQL標簽的所有資料添加至MappedStatement物件中
    builderAssistant.addMappedStatement(id, sqlSource, statementType, sqlCommandType,
                                        fetchSize, timeout, parameterMap, parameterTypeClass, resultMap, resultTypeClass,
                                        resultSetTypeEnum, flushCache, useCache, resultOrdered,
                                        keyGenerator, keyProperty, keyColumn, databaseId, langDriver, resultSets);
}

講解一下關于SQL陳述句的獲取,我們著重關注這一行代碼:

SqlSource sqlSource = langDriver.createSqlSource(configuration, context, parameterTypeClass);

這里LanguageDriver介面實作類是XMLLanguageDriver,再進入createSqlSource方法,又是熟悉的XxxBuilder物件,很明顯是用來決議SQL內容的,parseScriptNode方法最侄訓創建一個RawSqlSource物件,里面存盤一個BoundSql物件,而BoundSql物件才是真正存盤SQL陳述句的類,

在創建RawSqlSource物件的時候,會呼叫GenericTokenParser類中的parse方法來決議SQL陳述句中的通用標記(GenericToken),比如“#{ }”,并且將所有的通用標記都變為“?”占位符,

// XMLLanguageDriver類
public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType) {
    XMLScriptBuilder builder = new XMLScriptBuilder(configuration, script, parameterType);
    return builder.parseScriptNode();
}
// XMLScriptBuilder類
public SqlSource parseScriptNode() {
    MixedSqlNode rootSqlNode = parseDynamicTags(context);
    SqlSource sqlSource;
    if (isDynamic) {
        sqlSource = new DynamicSqlSource(configuration, rootSqlNode);
    } else {
        // 創建的是RawSqlSource物件,里面存有一個BoundSql物件
        sqlSource = new RawSqlSource(configuration, rootSqlNode, parameterType);
    }
    return sqlSource;
}
// 真正存盤SQL陳述句以及引數的物件
public class BoundSql {
    private final String sql;
    private final List<ParameterMapping> parameterMappings;
    private final Object parameterObject;
    private final Map<String, Object> additionalParameters;
    private final MetaObject metaParameters;
    
    // 省略其他內容...
}

進入到addMappedStatement方法,又是一個很長的方法,很明顯這里又使用了建造者模式,依靠MappedStatement類中的一個內部類Builder來構造MappedStatement物件,Configuration類中使用了一個Map集合來存盤所有的MappedStatement物件,Key值就是這個SQL標簽的id值,我們這里應該就是“getPaymentById”,Value值就是我們創建的對應的MapperStatement物件,

有個地方需要注意一下,在創建MapperStatement物件前會對id(即介面方法名)進行處理,在id前加上命名空間,也就成了該介面方法的全限定名,因此我們在呼叫selectOne等方法時應該填寫介面方法的全限定名,

其實我們決議XML檔案的目的就是把每個XML檔案中的所有增、刪、改、查SQL標簽決議成一個個MapperStatement,并把這些物件裝到Configuration的Map中備用,

public MappedStatement addMappedStatement(
    String id,
    SqlSource sqlSource,
    StatementType statementType,
    SqlCommandType sqlCommandType,
    Integer fetchSize,
    Integer timeout,
    String parameterMap,
    Class<?> parameterType,
    String resultMap,
    Class<?> resultType,
    ResultSetType resultSetType,
    boolean flushCache,
    boolean useCache,
    boolean resultOrdered,
    KeyGenerator keyGenerator,
    String keyProperty,
    String keyColumn,
    String databaseId,
    LanguageDriver lang,
    String resultSets) {

    if (unresolvedCacheRef) {
        throw new IncompleteElementException("Cache-ref not yet resolved");
    }

    // 修改存入Map集合的Key值為全限定名
    id = applyCurrentNamespace(id, false);
    boolean isSelect = sqlCommandType == SqlCommandType.SELECT;

    // 創建MappedStatement的構造器
    MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlSource, sqlCommandType)
        .resource(resource)
        .fetchSize(fetchSize)
        .timeout(timeout)
        .statementType(statementType)
        .keyGenerator(keyGenerator)
        .keyProperty(keyProperty)
        .keyColumn(keyColumn)
        .databaseId(databaseId)
        .lang(lang)
        .resultOrdered(resultOrdered)
        .resultSets(resultSets)
        .resultMaps(getStatementResultMaps(resultMap, resultType, id))
        .resultSetType(resultSetType)
        .flushCacheRequired(valueOrDefault(flushCache, !isSelect))
        .useCache(valueOrDefault(useCache, isSelect))
        .cache(currentCache);

    ParameterMap statementParameterMap = getStatementParameterMap(parameterMap, parameterType, id);
    if (statementParameterMap != null) {
        statementBuilder.parameterMap(statementParameterMap);
    }

    // 創建MappedStatement物件,并添加至Configuration物件中
    MappedStatement statement = statementBuilder.build();
    configuration.addMappedStatement(statement);
    return statement;
}

繼續回到XMLMapperBuilder類中的parse方法,當決議完一個XML檔案后就會把該檔案的路徑存入loadedResources集合中,

接下來我們看看bindMapperForNamespace方法,看名字就知道它的作用是通過命名空間系結mapper,一開始獲取名稱空間,名稱空間一般都是我們mapper的全限定名,它通過反射獲取這個mapper的Class物件,Configuration中維護了一個名為knownMappers的Map集合,Key值是我們剛才通過反射創建的Class物件,Value值則是通過動態代理創建的Class物件的代理物件,

因為knownMappers集合中還沒有存入我們創建的Class物件,所以會進入判斷陳述句,它先把名稱空間存到我們剛才存XML檔案路徑名的Set集合中,表示該命名空間已經加載過,然后再把mapper的Class物件存到knownMappers集合中,

public void parse() {
    if (!configuration.isResourceLoaded(resource)) {
        configurationElement(parser.evalNode("/mapper"));
        // 將決議完的XML檔案路徑存入Configuration的loadedResources集合中
        configuration.addLoadedResource(resource);
        // 通過名稱空間系結mapper
        bindMapperForNamespace();
    }
    
    parsePendingResultMaps();
    parsePendingCacheRefs();
    parsePendingStatements();
}

private void bindMapperForNamespace() {
    // 獲取到Mapper介面的全限定名
    String namespace = builderAssistant.getCurrentNamespace();
    if (namespace != null) {
        Class<?> boundType = null;
        try {
            // 通過全限定名創建該Mapper介面的Class物件
            boundType = Resources.classForName(namespace);
        } catch (ClassNotFoundException e) {
            // ignore, bound type is not required
        }
        if (boundType != null && !configuration.hasMapper(boundType)) {
			// 將命名空間的名稱存入已加載的Set集合中
            configuration.addLoadedResource("namespace:" + namespace);
            // 將Class物件存入Map集合中
            configuration.addMapper(boundType);
        }
    }
}
public class Configuration {
    protected final MapperRegistry mapperRegistry = new MapperRegistry(this);

    public <T> void addMapper(Class<T> type) {
        mapperRegistry.addMapper(type);
    }
}
public class MapperRegistry {
    private final Configuration config;
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();
    
    // 添加已注冊的Mapper介面的Class物件
    public <T> void addMapper(Class<T> type) {
        if (type.isInterface()) {
            if (hasMapper(type)) {
                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
            }
            boolean loadCompleted = false;
            try {
                knownMappers.put(type, new MapperProxyFactory<>(type));
                // It's important that the type is added before the parser is run
                // otherwise the binding may automatically be attempted by the
                // mapper parser. If the type is already known, it won't try.
                MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
                parser.parse();
                loadCompleted = true;
            } finally {
                if (!loadCompleted) {
                    knownMappers.remove(type);
                }
            }
        }
    }
    
    // 省略其他內容...
}

在存入Class物件的代理物件后,后面還有一步MapperAnnotationBuilder類的決議作業,我們進入到parse方法,可以看到它會使用Class物件的字串進行判斷該是否已經決議過該Class物件,通常這里是不會進入判斷的(下面的mapperClass方式才會進來),

public void parse() {
    String resource = type.toString();
    // 判斷該Mapper介面的Class物件是否已經決議過
    if (!configuration.isResourceLoaded(resource)) {
        loadXmlResource();
        configuration.addLoadedResource(resource);
		
        // 省略其他內容...
    }
    parsePendingMethods();
}

基于resource的方式講解完畢了,接下來就是url和mapperClass,url的方式和resource一樣,這里就不再贅述了,關于mapperClass,這種方式的決議步驟其實和resource是相反的,即先通過反射創建Mapper介面的Class物件,再通過Class物件的全限定名來尋找對應的XML映射檔案,

else if (resource == null && url == null && mapperClass != null) {
    // 反射創建Mapper介面的Class物件
    Class<?> mapperInterface = Resources.classForName(mapperClass);
    // 將該Class物件添加至knownMappers集合中
    configuration.addMapper(mapperInterface);
}
// Configuration類
public <T> void addMapper(Class<T> type) {
    mapperRegistry.addMapper(type);
}

mapperClass方式決議XML映射檔案和resource方式略有不同,mapperClass首先使用的是MapperAnnotationBuilder類進行決議,雖然看名字貌似該類只是負責注解的映射,但是其實暗藏玄機,

// MapperRegistry類
public <T> void addMapper(Class<T> type) {
    if (type.isInterface()) {
        if (hasMapper(type)) {
            throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
        }
        boolean loadCompleted = false;
        try {
            knownMappers.put(type, new MapperProxyFactory<>(type));
            // 使用的是MapperAnnotationBuilder決議器
            MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
            // mapperClass方式進行XML映射檔案的決議
            parser.parse();
            loadCompleted = true;
        } finally {
            if (!loadCompleted) {
                knownMappers.remove(type);
            }
        }
    }
}

我們進入到該類的parse方法,與resource方式不同的是這里會進入該判斷,并且執行了loadXmlResource方法,這個方法就是通過Class物件的名稱來加載XML映射檔案,loadXmlResource方法中首先也是進行一個判斷,這里肯定是沒有加載該XML映射檔案的命名空間的,后面有一行代碼非常關鍵,它將Class物件的名稱中所有的“.”替換為了“/”,然后拼接上了XML檔案的后綴,這表示MyBatis會在Mapper介面的同層級目錄來尋找對應的XML映射檔案,后面的步驟就和之前resource方式一樣了,通過XMLMapperBuilder類來決議,

這也解釋了為啥使用mapperClass方式時,XML映射檔案要與Mapper介面放在同一層級目錄下,

// MapperAnnotationBuilder
public void parse() {
    String resource = type.toString();
    if (!configuration.isResourceLoaded(resource)) {
        // 加載XML映射檔案
        loadXmlResource();
        // 加載完成后同樣存入Map集合中
        configuration.addLoadedResource(resource);
        assistant.setCurrentNamespace(type.getName());
        parseCache();
        parseCacheRef();
        for (Method method : type.getMethods()) {
            if (!canHaveStatement(method)) {
                continue;
            }
            if (getAnnotationWrapper(method, false, Select.class, SelectProvider.class).isPresent()
                && method.getAnnotation(ResultMap.class) == null) {
                parseResultMap(method);
            }
            try {
                parseStatement(method);
            } catch (IncompleteElementException e) {
                configuration.addIncompleteMethod(new MethodResolver(this, method));
            }
        }
    }
    parsePendingMethods();
}

// 通過Class物件的名稱來加載XML映射檔案
private void loadXmlResource() {
    if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
        // 構建XML映射檔案路徑
        String xmlResource = type.getName().replace('.', '/') + ".xml";
        // 后續步驟和resource方式一致
        InputStream inputStream = type.getResourceAsStream("/" + xmlResource);
        if (inputStream == null) {
            try {
                inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
            } catch (IOException e2) {
                // ignore, resource is not required
            }
        }
        if (inputStream != null) {
            XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
            xmlParser.parse();
        }
    }
}

至此,單檔案映射的加載已經講解完畢,接下里進入多檔案映射的加載!


最后再講講多檔案映射的加載,它首先或得XML所在的包名,然后呼叫configuration的addMappers物件,是不是有點眼熟,單檔案映射是addMapper,多檔案映射就是addMappers,

if ("package".equals(child.getName())) {
    String mapperPackage = child.getStringAttribute("name");
    configuration.addMappers(mapperPackage);
}

進入addMappers方法,就是通過ResolverUtil這個決議工具類找出該包下的所有mapper的名稱并通過反射創建mapper的Class物件裝進集合中,然后回圈呼叫addMapper(mapperClass)這個方法,這就和單檔案映射的Class型別一樣了,把mapper介面的Class物件作為引數傳進去,然后生成代理物件裝進集合然后再決議XML,

// Configuration類
public void addMappers(String packageName) {
    mapperRegistry.addMappers(packageName);
}
// MapperRegistry類
public void addMappers(String packageName) {
    addMappers(packageName, Object.class);
}

public void addMappers(String packageName, Class<?> superType) {
    ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>();
    resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
    Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
    for (Class<?> mapperClass : mapperSet) {
        // 后續步驟和單映射檔案加載一致
        addMapper(mapperClass);
    }
}
// ResolveUtil類
public ResolverUtil<T> find(Test test, String packageName) {
    String path = getPackagePath(packageName);
    try {
        List<String> children = VFS.getInstance().list(path);
        for (String child : children) {
            if (child.endsWith(".class")) {
                addIfMatching(test, child);
            }
        }
    } catch (IOException ioe) {
        log.error("Could not read package: " + packageName, ioe);
    }
    return this;
}

protected void addIfMatching(Test test, String fqn) {
    try {
        String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
        ClassLoader loader = getClassLoader();
        if (log.isDebugEnabled()) {
            log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
        }

        // 反射創建Class物件并存入Set集合中
        Class<?> type = loader.loadClass(externalName);
        if (test.matches(type)) {
            matches.add((Class<T>) type);
        }
    } catch (Throwable t) {
        log.warn("Could not examine class '" + fqn + "'" + " due to a "
                 + t.getClass().getName() + " with message: " + t.getMessage());
    }
}

終于把MyBatis的初始化步驟講完了,這里只是重點講解了<mappers>節點的決議,還有許多節點比如<environments>、<settings>、<typeAliases>等都大同小異,


第三步

這一步的主要目的就是通過之前初始化的SqlSessionFactory實作類來開啟一個SQL會話,

SqlSession sqlSession = sqlSessionFactory.openSession();

可以看出這里SqlSessionFactory實作類為DefaultSqlSessionFactory類,

public SqlSessionFactory build(Configuration config) {
    return new DefaultSqlSessionFactory(config);
}

我們知道SqlSession是我們與資料庫互動的頂級介面,所有的增刪改查都要通過SqlSession,所以進入DefaultSqlSessionFactory類的openSession方法,而openSession方法又呼叫了openSessionFromDataSource方法,

因為我們決議的XML主組態檔把所有的節點資訊都保存在了Configuration物件中,它開始直接獲得Environment節點的資訊,這個節點配置了資料庫的連接資訊和事務資訊,

之后通過Environment創建了一個事務工廠TransactionFactory,這里其實是實作類JdbcTransactionFactory,然后通過事務工廠實體化了一個事務物件Transaction,這里其實是實作類JdbcTransaction,在JdbcTransaction類中存有我們配置的資料庫環境相關資訊,例如資料源、資料庫隔離界別、資料庫連接以及是否自動提交事務,

public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private final Configuration configuration;

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

    @Override
    public SqlSession openSession() {
        return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
    }
    
    private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
        Transaction tx = null;
        try {
            // 通過Configuration物件獲取資料庫環境物件
            final Environment environment = configuration.getEnvironment();
            // 從資料庫環境物件中獲取事務工廠物件,呼叫方法在下面
            final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
            // 根據資料庫環境資訊創建事務物件
            tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
            final Executor executor = configuration.newExecutor(tx, execType);
            return new DefaultSqlSession(configuration, executor, autoCommit);
        } catch (Exception e) {
            closeTransaction(tx); // may have fetched a connection so lets call close()
            throw ExceptionFactory.wrapException("Error opening session.  Cause: " + e, e);
        } finally {
            ErrorContext.instance().reset();
        }
    }
    
    // 從資料庫環境物件中獲取事務工廠物件,如果沒有就新建一個
    private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
        if (environment == null || environment.getTransactionFactory() == null) {
            return new ManagedTransactionFactory();
        }
        return environment.getTransactionFactory();
    }
    
    // 省略其他內容...
}

默認情況下,不會傳入Connection引數,而是等到使用時才通過DataSource創建Connection物件,

public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
    dataSource = ds;
    level = desiredLevel;
    autoCommit = desiredAutoCommit;
}

public Connection getConnection() throws SQLException {
    // 使用時才創建Connection
    if (connection == null) {
        openConnection();
    }
    return connection;
}

protected void openConnection() throws SQLException {
    if (log.isDebugEnabled()) {
        log.debug("Opening JDBC Connection");
    }
    connection = dataSource.getConnection();
    if (level != null) {
        connection.setTransactionIsolation(level.getLevel());
    }
    setDesiredAutoCommit(autoCommit);
}

重點來了,最后他創建了一個執行器Executor ,我們知道SqlSession是與資料庫互動的頂層介面,SqlSession中會維護一個Executor來負責SQL生產和執行和查詢快取等,

由原始碼可知最終它是創建一個SqlSession實作類DefaultSqlSession,并且維護了一個Executor實體,

// DefaultSqlSessionFactory類中關于創建Excutor和SqlSession的代碼片段
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
public class DefaultSqlSession implements SqlSession {
    private final Configuration configuration;
    // 維護了一個Executor實體
    private final Executor executor;
    private final boolean autoCommit;
    private boolean dirty;
    private List<Cursor<?>> cursorList;
    
    // 省略其他內容...
}

我們再來看看這個執行器的創建程序,其實就是判斷生成哪種執行器,defaultExecutorType默認指定使用SimpleExecutor,

MyBatis有三種的執行器:

  1. SimpleExecutor(默認),

  2. ReuseExecutor,

  3. BatchExecutor,

SimpleExecutor:簡單執行器,

是MyBatis中默認使用的執行器,每執行一Update或Select,就開啟一個Statement物件(或PreparedStatement物件),用完就直接關閉Statement物件(或PreparedStatment物件),

ReuseExecutor:可重用執行器,

這里的重用指的是重復使用Statement(或PreparedStatement),它會在內部使用一個Map把創建的Statement(或PreparedStatement)都快取起來,每次執行SQL命令的時候,都會去判斷是否存在基于該SQL的Statement物件,如果存在Statement物件(或PreparedStatement物件)并且對應的Connection還沒有關閉的情況下就繼續使用之前的Statement物件(或PreparedStatement物件),并將其快取起來,

因為每一個SqlSession都有一個新的Executor物件,所以我們快取在ReuseExecutor上的Statement作用域是同一個SqlSession,

BatchExecutor:批處理執行器,

用于將多個SQL一次性輸出到資料庫,

 public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
    executorType = executorType == null ? defaultExecutorType : executorType;
    executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
    Executor executor;
     // 選擇執行器
    if (ExecutorType.BATCH == executorType) {
        executor = new BatchExecutor(this, transaction);
    } else if (ExecutorType.REUSE == executorType) {
        executor = new ReuseExecutor(this, transaction);
    } else {
        executor = new SimpleExecutor(this, transaction);
    }
    if (cacheEnabled) {
        executor = new CachingExecutor(executor);
    }
    executor = (Executor) interceptorChain.pluginAll(executor);
    return executor;
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/234987.html

標籤:Java

上一篇:MyBatis詳細原始碼決議(上篇)

下一篇:spring事務相關

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more