1. 程式人生 > 實用技巧 >AcWing 1135. 新年好 圖論 列舉

AcWing 1135. 新年好 圖論 列舉

Mybatis介紹

  • MyBatis 是一款優秀的持久層框架

  • 它支援定製化 SQL、儲存過程以及高階對映。

  • MyBatis 避免了幾乎所有的 JDBC 程式碼和手動設定引數以及獲取結果集。

  • MyBatis 可以使用簡單的 XML 或註解來配置和對映原生型別、介面和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 物件)為資料庫中的記錄。

  • MyBatis 本是apache的一個開源專案iBatis, 2010年這個專案由apache software foundation 遷移到了google code,並且改名為MyBatis 。

  • 2013年11月遷移到Github。

  • 獲得Mybatis

  • maven倉庫:

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    

使用流程

  • 新建一個Maven專案
  • 匯入依賴
  • 修改pom配置檔案
<?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>org.example</groupId>
    <artifactId>Mybatis-Study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>Mybatis-01</module>
    </modules>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>


  • 編寫mybatis的核心配置檔案
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    // 註冊核心配置檔案
    <mappers>
        <mapper resource="dao/UserMapper.xml"/>
    </mappers>
</configuration>
  • 編寫mybatis工具類
//sqlSessionFactory --> sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static{
        try {
            //使用Mybatis第一步:獲取sqlSessionFactory物件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //既然有了 SqlSessionFactory,顧名思義,我們就可以從中獲得 SqlSession 的例項了。
    // SqlSession 完全包含了面向資料庫執行 SQL 命令所需的所有方法。
    public static SqlSession  getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}
  • 編寫介面
  • 編寫mapping配置檔案
<?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <!--namespace=繫結一個對應的Dao/Mapper介面-->
    <mapper namespace="dao.UserDao">
<!--select查詢語句-->
    <select id="getUserList" resultType="pojo.User">
        select * from mybatis.user
    </select>
</mapper>

CRUD

  • namespace:namespace中的包名要和 Dao/mapper 介面的包名一致!

  • select、insert、update、delete

選擇,查詢語句;

  • id : 就是對應的namespace中的方法名;
  • resultType:Sql語句執行的返回值!
  • parameterType : 引數型別!
  • 增刪改需要提交事務

  • 使用map傳遞引數

    //萬能的Map
    int addUser2(Map<String,Object> map);


    <!--物件中的屬性,可以直接取出來    傳遞map的key-->
    <insert id="addUser" parameterType="map">
        insert into mybatis.user (id, pwd) values (#{userid},#{passWord});
    </insert>
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    Map<String, Object> mp = new HashMap<String, Object>();
    mp.put("userid", 2);
    mp.put("userName", "Kawhi Leonard");
    mp.put("password", "223333");

    int res = mapper.addUser2(mp);
    if(res > 0) {
        System.out.println("Success!");
    }

    sqlSession.commit();
    sqlSession.close();
  • 模糊查詢
  1. Java程式碼執行的時候,傳遞萬用字元 % %

    List<User> userList = mapper.getUserLike("%李%");
    
  2. 在sql拼接中使用萬用字元!

    select * from mybatis.user where name like "%"#{value}"%"
    

配置

  • 核心配置檔案:mybatis-config.xml

  • Environments: 可以配置成多種環境,但SQLSessionFactory例項只能選擇一種環境

預設的事務管理器: JDBC, 連線池:POOLED

  • properties:實現引用的配置檔案、優先使用外部檔案、可增加屬性配置

db.properties:

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useSSL=true&useUnicode=true&characterEncoding=utf8&useSSL=true
    username=root
    password=root

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="db.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="dao/UserMapper.xml"/>
    </mappers>
</configuration>
  • typeAliases:別名, java型別設定一個短名字,用於減少完全限定名的冗餘
  1. 給實體類起別名: 實體類較少
<typeAliases>
    <typeAlias type="pojo.User" alias="User"/>
</typeAliases>
  1. 指定一個包名:實體類較多
    掃描實體類的包,預設的別名就是這個類的類名,首字母小寫
<typeAliases>
    <package name="pojo"/>
</typeAliases>

可在第二種方式上加註解

@Alias("user")
public class User{}
  • 設定
  • mappers 對映器
  1. resource: 推薦使用
  2. class: 介面實現類的完全限定類名
    注意:介面和mapper配置檔案必須同名、必須在同一個包內\
  3. name: 將包內的對映器介面實現全部註冊為對映器
    注意:介面和mapper配置檔案必須同名、必須在同一個包內\
  • 生命週期和作用域:錯誤使用會導致嚴重併發問題

start -> SqlSessionFactoryBuilder -> SqlSessionFactory -> SqlSession -> mapper -> end

  1. SqlSessionFactoryBuilder一旦建立,就不再用了, 區域性變數
  2. SqlSessionFactory -> 資料庫連線池 :執行期間一直存在、沒有理由丟棄他或重新建立另外一個例項, 最佳作用域:應用作用域,使用單例模式或靜態單例模式
  3. SqlSession -> 連線到連線池的一個請求,不能被共享,用完需要關閉

解決屬性名和欄位名不一致的問題

    <resultMap id="UserMap" type="User">
        // column 對應資料庫中的欄位名, property 對應實體類中的欄位名
        <!-- <result column="id" property="id"/>
        <result column="name" property="name"/> -->
        <result column="pwd" property="password"/>
    </resultMap>

    <select id="getUserById" parameterType="int" resultMap="UserMap">
        select * from mybatis.user where id = #{id};
    </select>

日誌

日誌工廠:用於排錯

  • LOG4J
   <settings>
       <setting name="logImpl" value=""/>
   </settings>
  • STDOUT_LOGGING :標準
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

分頁:減少資料處理量

limit(推薦使用)

    List<User> getUserByLimit(Map<String, Integer> mp);
<select id="getUserByLimit" parameterType="map"  resultType="User">
        select * from mybatis.user limit #{startIndex}, #{pageSize};
    </select>

rowBounds

不再使用SQL實現分頁

  1. 介面

    //分頁2
    List<User> getUserByRowBounds();
    
  2. mapper.xml

    <!--分頁2-->
    <select id="getUserByRowBounds" resultMap="UserMap">
        select * from  mybatis.user
    </select>
    
  3. 測試

    @Test
     public void getUserByRowBounds() {
         SqlSession sqlSession = MybatisUtils.getSqlSession();
    
     //RowBounds實現
         RowBounds rowBounds = new RowBounds(1, 2);
    
     //通過Java程式碼層面實現分頁
         List<User> userList = sqlSession.selectList("com.kuang.dao.UserMapper.getUserByRowBounds",null,rowBounds);
    
         for (User user : userList) {
             System.out.println(user);
         }
    
         sqlSession.close();
     }
    

使用註解開發

  • 面向介面開發:定義與實現的分離
  • 使用註解對映簡單的語句會使程式碼變得簡潔,但對於複雜的語句,建議使用xml對映語句
  • 本質是利用了反射機制
  • 底層是代理模式

Mybatis執行流程

Resources獲取全域性配置檔案 -> 例項化SQLSessionFactoryBuilder構造器 -> 解析配置檔案流 -> Configuration所有配置資訊 -> SQLSessionFactory例項化 ->transaction事務管理 -> 建立executor執行器 -> 建立SQLSession -> 實現CRUD -> 提交事務or回滾

使用註解實現CRUD

@Select("select * from user")
List<User> getUsers();

// 多個基本資料型別的引數必須使用@Params
@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);

@Insert("insert into user(id, name, pwd) values(#{id}, #{name}, #{password})")
int addUser(User user);

@Update("update user set name=#{name}, pwd=#{password} where id = #{id}")
int updateUser(User user);

@Delete("delete from user where id = #{uid}")
int deleteUser(@Params("uid") int id);
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 自動提交事務
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }
}

@Params()註解:

  • 基本型別引數需要加上
  • 引用型別不用加
  • 如果只有一個基本型別、可以忽略
  • 在Sql中引用的就是@Params中設定的屬性

lombok

@Data:無參構造,get、set、tostring、hashcode,equals
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@Getter

複雜查詢環境搭建

多對一關係:多個學生對應一個老師

方式一:按照查詢巢狀處理
  • 查詢所有學生
  • 根據每個查詢出來的tid,找到對應的老師
<select id="getStudent" resultMap="StudentTeacher">
    select * from student;
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!-- 物件用association, 集合用collection -->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{id};
</select>
方式二:按照結果巢狀處理
<select id="getStudent2" resultMap="StudentTeacher2">
    SELECT s.`id` sid, s.`name` sname, t.`name` tname
    FROM student s, teacher t
    WHERE s.tid = t.`id`;
</select>

<resultMap id="StudentTeacher2" type="Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

一對多關係:一個老師擁有多個學生

按照結果巢狀
<select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.name tname, t.id tid
        from student s, teacher t
        where s.tid = t.id and t.id = #{id};
</select>

<resultMap id="TeacherStudent" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>
子查詢
<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from teacher where id = #{id};
</select>

<resultMap id="TeacherStudent2" type="Teacher">
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="student">
    select * from student where tid = #{tid};
</select>
  • 關聯-association
  • 集合-collection
  • javaType:指定實體類屬性的型別
  • ofType: 用來指定對映到List或集合中的pojo實體類

動態SQL:根據不同的條件生成不同是SQL

  • IF
<select id="queryBlogIF" parameterType="map" resultType="Blog">
    select * from blog where 1=1
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author">
        and author = #{author}
    </if>
</select>
  • where
<select id="queryBlogIF" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author">
            and author = #{author}
        </if>
    </where>
</select>
  • choose:相當於java中的switch
  • set:智慧增刪逗號
  • sql:程式碼複用,抽取公共部分
<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author">
        and author = #{author}
    </if>
</sql>


<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <include refit="if-title-author"></include>
    </where>
</select>
  • foreach:對一個集合進行遍歷
select * from user where 1=1 and 
  <foreach item="id" collection="ids"
      open="(" separator="or" close=")">
        #{id}
  </foreach>
(id=1 or id=2 or id=3)

<!--
        select * from mybatis.blog where 1=1 and (id=1 or id = 2 or id=3)

        我們現在傳遞一個萬能的map , 這map中可以存在一個集合!
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
    select * from mybatis.blog
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>

快取

查詢 : 連線資料庫 ,耗資源!
一次查詢的結果,給他暫存在一個可以直接取到的地方!--> 記憶體 : 快取

  1. 什麼是快取 [ Cache ]?

    • 存在記憶體中的臨時資料。
    • 將使用者經常查詢的資料放在快取(記憶體)中,使用者去查詢資料就不用從磁碟上(關係型資料庫資料檔案)查詢,從快取中查詢,從而提高查詢效率,解決了高併發系統的效能問題。
  2. 為什麼使用快取?

    • 減少和資料庫的互動次數,減少系統開銷,提高系統效率。
  3. 什麼樣的資料能使用快取?

    • 經常查詢並且不經常改變的資料。【可以使用快取】

快取失效的情況:

  1. 查詢不同的東西
  2. 增刪改操作,可能會改變原來的資料,所以必定會重新整理快取!
  3. 查詢不同的Mapper.xml
  4. 手動清理快取!

小結:一級快取預設是開啟的,只在一次SqlSession中有效,也就是拿到連線到關閉連線這個區間段!

一級快取就是一個Map。

  • 二級快取
  • 二級快取也叫全域性快取,一級快取作用域太低了,所以誕生了二級快取
  • 基於namespace級別的快取,一個名稱空間,對應一個二級快取;
  • 工作機制
    • 一個會話查詢一條資料,這個資料就會被放在當前會話的一級快取中;
    • 如果當前會話關閉了,這個會話對應的一級快取就沒了;但是我們想要的是,會話關閉了,一級快取中的資料被儲存到二級快取中;
    • 新的會話查詢資訊,就可以從二級快取中獲取內容;
    • 不同的mapper查出的資料會放在自己對應的快取(map)中;

步驟:

  1. 開啟全域性快取

    <!--顯示的開啟全域性快取-->
    <setting name="cacheEnabled" value="true"/>
    
  2. 在要使用二級快取的Mapper中開啟

    <!--在當前Mapper.xml中使用二級快取-->
    <cache/>
    

    也可以自定義引數

    <!--在當前Mapper.xml中使用二級快取-->
    <cache  eviction="FIFO"
           flushInterval="60000"
           size="512"
           readOnly="true"/>
    

小結:

  • 只要開啟了二級快取,在同一個Mapper下就有效
  • 所有的資料都會先放在一級快取中;
  • 只有當會話提交,或者關閉的時候,才會提交到二級緩衝中!
  • 快取原理
  1. 每一個SQLSession都有一級快取, 第一次查詢訪問資料庫、放到一級快取中
  2. 當SQLSession關閉時,其中的一級快取放入Mapper的二級快取中

快取順序:

  1. 先看二級快取有沒有
  2. 再看一級快取有沒有
  3. 查資料庫