主頁 > 後端開發 > day01-Mybatis介紹與入門

day01-Mybatis介紹與入門

2023-02-23 06:53:48 後端開發

Mybatis介紹與入門

1.官方檔案

Mybatis中文手冊:mybatis – MyBatis 3 或者 MyBatis中文網

Maven倉庫:Maven Repository: org.mybatis ? mybatis ? 3.5.7 (mvnrepository.com)

2.概述

2.1傳統Java程式操作DB

image-20230221194213005

傳統方式操作資料庫的問題:

  1. 需要自己去連接資料庫,這段代碼由程式員撰寫(不一定標準)

  2. 程式不是OOP的方式來操作DB(我們希望在代碼層面上是以物件的形式來操作,如insert(Object))

  3. SQL陳述句寫在程式中,屬于硬編碼,沒有解耦

2.2Mybatis基本介紹

  1. Mybatis 是一個持久層框架
  2. 前身是 ibatis,在ibatis3.x 時,更名為Mybatis
  3. Mybatis 在 Java 和 sql 之間提供更加靈活的映射方案
  4. mybatis 可以對資料庫表的操作(sql,方法)等等直接剝離,寫到 xml 組態檔,實作和 java 代碼的解耦
  5. mybatis 通過 SQL 操作 DB,建庫建表的操作仍需要程式員完成

2.3Mybatis作業原理

image-20230221202111256

相對于傳統方式,Mybatis的優勢:

  1. 資料庫的連接/連接池,只需要配置即可,標準可以統一
  2. 程式以OOP的方式來操作資料庫
  3. sql陳述句可以寫在xml檔案中,實作了解耦
  4. Mybatis可以對DB操作進行優化,提高效率,比如配置快取

3.Mybatis快速入門

3.1需求說明

要求:開發一個Mybatis專案,通過Mybatis的方式可以對monster表進行crud操作,

3.2環境搭建

(1)創建maven父專案,方便專案的jar包管理

image-20230221212409791
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.li</groupId>
    <artifactId>mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <!--加入依賴-->
    <dependencies>
        <!--mysql依賴-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!--mybatis依賴-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!--junit依賴-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <!--指定該jar的作用范圍在test目錄下-->
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

(2)創建maven父專案的Module,視為子專案

image-20230221212736703 image-20230221212828200

image-20230221213115557 image-20230221214918038

此時父專案的pom.xml檔案如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!--說明:
        1.將 mybatis作為父專案管理多個子模塊/子專案
        2.父專案的完整的坐標 groupId[組織名]+artifactId[專案名]
        3.后面該父專案會管理多個子模塊/子專案,將來父專案中的引入的依賴可以直接給子專案用,
            這樣開發簡單,提高復用性,也便于管理
        4.<packaging>pom</packaging> 表示父專案以多個子模塊/子專案管理工程
        5. 在 modules指定管理哪些子模塊
     -->
    <groupId>com.li</groupId>
    <artifactId>mybatis</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis_quickstart</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    
    <!--加入依賴,略,詳見上面-->
    <dependencies>
        <!--mysql依賴-->
        <!--mybatis依賴-->
        <!--junit依賴-->
    </dependencies>
</project>

子模塊的pom.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <!--說明
        1.parent指定了該模塊的父專案的坐標 artifactId+groupId
        2.這樣配置后,子模塊就可以使用到父專案的依賴
        -->
    <parent>
        <artifactId>mybatis</artifactId>
        <groupId>com.li</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <!--子模塊的名稱,當前子模塊的groupId默認和父專案的groupId相同,即com.li-->
    <artifactId>mybatis_quickstart</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>

3.2代碼實作

image-20230222174845793

(1)創建資料庫和表

-- 創建資料庫
CREATE DATABASE `mybatis`;
USE `mybatis`;
-- 創建monster表
CREATE TABLE `monster`(
`id` INT NOT NULL AUTO_INCREMENT,
`age` INT NOT NULL,
`birthday` DATE DEFAULT NULL,
`email` VARCHAR(255) NOT NULL,
`gender` TINYINT NOT NULL,-- 1 male, 0 female
`name` VARCHAR(255) NOT NULL,
`salary` DOUBLE NOT NULL,
PRIMARY KEY(`id`)
)CHARSET=utf8

(2)在子模塊 mybatis_quickstart 的 resources 目錄創建組態檔 mybatis-config.xml(名稱隨意)

mybatis組態檔模板

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <!--配置事務管理器-->
            <transactionManager type="JDBC"/>
            <!--配置資料源-->
            <dataSource type="POOLED">
                <!--配置驅動-->
                <property name="driver" value="https://www.cnblogs.com/liyuelian/archive/2023/02/22/com.mysql.jdbc.Driver"/>
                <!--配置連接mysql的url
                    1.jdbc:mysql 協議
                    2.127.0.0.1:3306 連接資料庫的 ip+port
                    3.mybatis 連接的資料庫名稱
                    4.useSSL=true 表示使用安全連接
                    5.&amp; 表示 & 符號,這里這樣寫是為了轉義,防止決議錯誤
                    6.useUnicode=true 使用Unicode,防止編碼錯誤
                    7.characterEncoding=UTF-8 使用utf-8,防止中文亂碼
                    -->
                <property name="url" value="https://www.cnblogs.com/liyuelian/archive/2023/02/22/jdbc:mysql://127.0.0.1:3306/mybatis?
                    useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
                <!--用戶名-->
                <property name="username" value="https://www.cnblogs.com/liyuelian/archive/2023/02/22/root"/>
                <!--密碼-->
                <property name="password" value="https://www.cnblogs.com/liyuelian/archive/2023/02/22/123456"/>
            </dataSource>
        </environment>
    </environments>
    <!--這里配置需要管理的mapper.xml檔案-->
    <mappers>
        <mapper resource="com/li/mapper/MonsterMapper.xml"/>
    </mappers>
</configuration>

(3)創建物體類 Monster.java

package com.li.entity;

import java.util.Date;

/**
 * @author 李
 * @version 1.0
 * 1.Monster和 monster表有對應關系
 * 2.原生的sql陳述句查詢結果還是要封裝成物件
 * 3.因此要求這里的物體類屬性名和表的欄位名保持相同
 */
public class Monster {
    //屬性和表的欄位對應
    private Integer id;
    private Integer age;
    private String name;
    private String email;
    private Date birthday;
    private double salary;
    private Integer gender;

    public Monster() {
    }

    public Monster(Integer id, Integer age, String name, String email,
                   Date birthday, double salary, Integer gender) {
        this.id = id;
        this.age = age;
        this.name = name;
        this.email = email;
        this.birthday = birthday;
        this.salary = salary;
        this.gender = gender;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Monster{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", birthday=" + birthday +
                ", salary=" + salary +
                ", gender=" + gender +
                '}';
    }
}

(4)創建MonsterMapper介面

package com.li.mapper;

import com.li.entity.Monster;

/**
 * @author 李
 * @version 1.0
 * 1.MonsterMapper介面用于宣告操作monster表的方法
 * 2.這些方法可以通過注解或者xml檔案來實作
 */
public interface MonsterMapper {
    //添加monster
    public void addMonster(Monster monster);
}

(5)創建介面對應的映射檔案,實作方法

mybatis – MyBatis 3 | XML 映射器

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--說明
  1.這是一個mapper.xml檔案
  2.該檔案可以去實作對應的介面的方法
  3.namespace 指定當前xml檔案和哪個介面對應!
-->
<mapper namespace="com.li.mapper.MonsterMapper">
    <!--配置addMonster方法
     1.id 就是對應介面的方法名
     2.parameterType 方法的入參
     3.寫入sql陳述句
     4.(`age`,`birthday`,`email`,`gender`,`name`,`salary`) 表的欄位
     5.#{age},#{birthday},#{email},#{gender},#{name},#{salary} 從傳入的Monster物件屬性中獲取
     6.注意這里的 #{age}對應Monster物件的屬性名,其他類推
     -->
    <insert id="addMonster" parameterType="com.li.entity.Monster">
        INSERT INTO `monster`
        (`age`,`birthday`,`email`,`gender`,`name`,`salary`)
        VALUES (#{age},#{birthday},#{email},#{gender},#{name},#{salary})
    </insert>
</mapper>

(6)工具類MybatisUtils,用于獲取連接

package com.li.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 李
 * @version 1.0
 * MybatisUtils工具類可以得到 SqlSession
 */
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    //靜態代碼塊中初始化 SqlSessionFactory-會話工廠
    static {
        try {
            //指定資源檔案(組態檔)
            String resource = "mybatis-config.xml";
            //獲取組態檔對應的inputStream
            //說明:加載檔案時,默認到resource目錄對應的==>運行后的作業目錄target/classes找
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
            System.out.println("sqlSessionFactory=" + sqlSessionFactory.getClass());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //撰寫方法,回傳一個SqlSession物件-會話
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}

3.3測驗

3.3.1添加

test 目錄中創建測驗類 MonsterMapperTest.java

package com.li.mapper;

import com.li.entity.Monster;
import com.li.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

/**
 * @author 李
 * @version 1.0
 */
public class MonsterMapperTest {
    //屬性
    private SqlSession sqlSession;
    private MonsterMapper monsterMapper;

    /**
     * 撰寫方法,完成初始化
     * 當一個A方法標注了注解 @Before時,表示在執行你的目標測驗方法前會先執行A方法
     */
    @Before
    public void init() {
        sqlSession = MybatisUtils.getSqlSession();
        //獲取到 monsterMapper物件 =class com.sun.proxy.$Proxy7代理物件)
        //底層使用了動態代理機制,回傳一個代理物件,通過這個物件去執行你的方法
        monsterMapper = sqlSession.getMapper(MonsterMapper.class);
        System.out.println("monsterMapper的型別=" + monsterMapper.getClass());
    }

    @Test
    public void addMonster() {
        for (int i = 0; i < 2; i++) {
            Monster monster = new Monster();
            monster.setAge(10 + i);
            monster.setBirthday(new Date());
            monster.setEmail("[email protected]");
            monster.setGender(1);
            monster.setName("松鼠精" + i + "號");
            monster.setSalary(1000 + i * 10);
            monsterMapper.addMonster(monster);
            System.out.println("添加物件--" + monster);
        }
        //如果是增刪改,需要提交事務,因為它默認不提交
        if (sqlSession != null) {
            sqlSession.commit();
            //將連接釋放回連接池
            sqlSession.close();
        }
        System.out.println("保存成功....");
    }
}

上面的代碼一般會出現找不到xxxmapper.xml錯誤,原因是加載的資源檔案時是到target目錄下加載的,當maven專案運行時,源工程的MonsterMapper.xml并沒有被拷貝到target目錄下,

解決方法:在父工程的pom.xml加入build配置,作用是配置resource,防止資源匯出失敗

<!--將指定的目錄以及它們的子目錄下的xml、properties檔案在build專案時
    匯出到對應的target目錄下-->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.xml</include>
                <include>**/*.properties</include>
            </includes>
        </resource>
    </resources>
</build>

然后選擇build project

image-20230222170542190

如果不行,可能是maven版本沖突,在setting中切換maven版本,然后點擊父工程的maven的clean重新構建,

image-20230222170746607 image-20230222170841032


測驗結果:

image-20230222172401382

資料庫monster表增加了兩條記錄:

image-20230222172603869

3.3.2回傳自增長

有時候我們需要獲取資料庫中自動生成(AUTO_INCREMENT)的主鍵,這時候可以使用Mybatis的useGeneratedKeys (開啟新增主鍵回傳功能)和 keyProperty(物體的主鍵屬性)來配合獲取,

(1)修改映射檔案MonsterMapper.xml,在該檔案中的方法映射中添加 useGenerateKeys 和 keyProperty

<mapper namespace="com.li.mapper.MonsterMapper">
    <insert id="addMonster" parameterType="com.li.entity.Monster" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO `monster`
        (`age`,`birthday`,`email`,`gender`,`name`,`salary`)
        VALUES (#{age},#{birthday},#{email},#{gender},#{name},#{salary})
    </insert>
</mapper>

(2)修改測驗類,輸出主鍵

image-20230222174200121

(3)測驗結果:

image-20230222174250749

資料庫表格:

image-20230222174333155

3.3.3洗掉

(1)修改 MonsterMapper.java 介面,宣告 delMonster() 方法

//根據id洗掉一個Monster
public void delMonster(Integer id);

(2)在映射檔案 MonsterMapper.xml 中實作 delMonster() 方法

<!--配置delMonster方法
    1.java.lang.Integer是Java型別,可以簡寫為Integer
    2.寫入delete陳述句
 -->
<delete id="delMonster" parameterType="Integer">
    DELETE FROM `monster` WHERE `id`=#{id};
</delete>

(3)修改測驗類,添加測驗方法

package com.li.mapper;

import com.li.entity.Monster;
import com.li.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;

/**
 * @author 李
 * @version 1.0
 */
public class MonsterMapperTest {
    //屬性
    private SqlSession sqlSession;
    private MonsterMapper monsterMapper;

    @Before
    public void init() {
        sqlSession = MybatisUtils.getSqlSession();
        monsterMapper = sqlSession.getMapper(MonsterMapper.class);
        System.out.println("monsterMapper的型別=" + monsterMapper.getClass());
    }

    @Test
    public void delMonster() {
        //洗掉id=2的記錄
        monsterMapper.delMonster(2);
        //如果是增刪改操作,需要提交事務,因為它默認不提交
        if (sqlSession != null) {
            sqlSession.commit();
            //將連接釋放回連接池
            sqlSession.close();
        }
        System.out.println("洗掉成功....");
    }
}

測驗結果:

image-20230222180136664

資料庫id=2的記錄成功被洗掉:

image-20230222180212704

3.3.4修改&查詢

(1)修改 MonsterMapper.java 介面,宣告修改和查詢的方法

//修改Monster
public void updateMonster(Monster monster);
//查詢-根據id
public Monster getMonsterById(Integer id);
//查詢所有的Monster
public List<Monster> findAllMonster();

(2) 映射檔案 MonsterMapper.xml 中實作方法

<!--配置/實作updateMonster方法
    這里的入參可以使用型別別名,為Java型別設定一個縮寫名字,可以降低冗余的全限定類名的書寫
    型別別名在mybatis的組態檔中配置,而不是當前的檔案-->
<update id="updateMonster" parameterType="Monster">
    UPDATE `monster`
    SET `age`=#{age},`birthday`=#{birthday},`email`=#{email},
    `gender`=#{gender},`name`=#{name},`salary`=#{salary}
    WHERE `id`=#{id};
</update>

<!--配置/實作getMonsterById方法,
resultType 期望從這條陳述句中回傳結果的類全限定名或別名,
注意,如果回傳的是集合,那應該設定為集合包含的型別,而不是集合本身的型別,-->
<select id="getMonsterById" resultType="Monster">
    SELECT * FROM `monster` WHERE id=#{id};
</select>

<!--實作findAllMonster方法
如果回傳的是集合,那應該設定為集合包含的型別,而不是集合本身的型別-->
<select id="findAllMonster" resultType="Monster">
    SELECT * FROM `monster`;
</select>

(3)配置別名

image-20230222183412387

(4)修改測驗類,添加測驗方法

package com.li.mapper;

import com.li.entity.Monster;
import com.li.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;

import java.util.Date;
import java.util.List;

/**
 * @author 李
 * @version 1.0
 */
public class MonsterMapperTest {
    //屬性
    private SqlSession sqlSession;
    private MonsterMapper monsterMapper;

    @Before
    public void init() {
        sqlSession = MybatisUtils.getSqlSession();
        monsterMapper = sqlSession.getMapper(MonsterMapper.class);
        System.out.println("monsterMapper的型別=" + monsterMapper.getClass());
    }
    
    @Test
    public void updateMonster() {
        Monster monster = new Monster();
        monster.setAge(50);
        monster.setBirthday(new Date());
        monster.setEmail("[email protected]");
        monster.setGender(0);
        monster.setName("白骨精");
        monster.setSalary(20000);
        monster.setId(3);
        monsterMapper.updateMonster(monster);
        if (sqlSession != null) {
            sqlSession.commit();
            sqlSession.close();
        }
        System.out.println("修改成功..");
    }

    @Test
    public void getMonsterById() {
        Monster monster = monsterMapper.getMonsterById(3);
        System.out.println("monster=" + monster);
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    @Test
    public void findAllMonster() {
        List<Monster> monsters = monsterMapper.findAllMonster();
        for (Monster monster : monsters) {
            System.out.println("monster="+monster);
        }
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}

測驗updateMonster()方法:

image-20230222182453471 image-20230222182516361

測驗getMonsterById()方法:

image-20230222184234892

測驗findAllMonster()方法:

image-20230222184621483

4.日志輸出-查看SQL

在開發Mybatis程式時,比如執行測驗方法,程式員往往需要查看底層發給MySql的SQL陳述句到底長什么樣,這時應該如何查看?

解決方案:日志輸出,

image-20230222190341884

(1)修改Mybatis-config.xml檔案,加入日志輸出配置,方便分析SQL陳述句

image-20230222190744642

(2)比如測驗updateMonster() 方法時,輸出的結果為:

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
sqlSessionFactory=class org.apache.ibatis.session.defaults.DefaultSqlSessionFactory
monsterMapper的型別=class com.sun.proxy.$Proxy7
Opening JDBC Connection
Wed Feb 22 19:09:14 CST 2023 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Created connection 1475491159.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@57f23557]
==>  Preparing: UPDATE `monster` SET `age`=?,`birthday`=?,`email`=?, `gender`=?,`name`=?,`salary`=? WHERE `id`=?;
==> Parameters: 50(Integer), 2023-02-22 19:09:14.079(Timestamp), [email protected](String), 0(Integer), 白骨精(String), 20000.0(Double), 3(Integer)
<==    Updates: 1
Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@57f23557]
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@57f23557]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@57f23557]
Returned connection 1475491159 to pool.
修改成功..

Process finished with exit code 0

當進行多表聯查的時候,日志輸出對我們的除錯很有幫助,

5.練習

image-20230222192639018

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

標籤:其他

上一篇:為了快速了解原神,我用Python爬取了原神所有角色資訊!

下一篇:Python迭代器是啥?

標籤雲
其他(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