Mybatis の基本を理解する

Jan 22, 2021 am 09:29 AM

Mybatis の基本を理解する

無料学習の推奨事項: mysql ビデオ チュートリアル

# #mybatis

mybatis-config.xml の詳細な設定 (設定するときは、冗長な属性を削除する必要があり、中国語を含めることはできません。そうしないと、エラーが報告されます。)

<?xml  version="1.0" encoding="UTF-8" ?>nbsp;configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd"><!--configuration核心配置  配置文件的根元素 --><configuration>
    <!-- 属性:定义配置外在化 -->
    <properties></properties>
    <!-- 设置:定义mybatis的一些全局性设置 -->
    <settings>
        <!-- 具体的参数名和参数值 -->
        <setting></setting>
    </settings>
    <!-- 类型名称:为一些类定义别名 -->
    <typealiases>
        <!-- 实体类少 建议 第一种取别名方式-->
        <typealias></typealias>
        <!--实体类多 建议  第二种取别名方式
        默认情况下用这种方式 别名为类名 首字母最好小写
        -->
        <package></package>
    </typealiases>
    <!-- 类型处理器:定义Java类型与数据库中的数据类型之间的转换关系 -->
    <typehandlers></typehandlers>
    <!-- 对象工厂 -->
    <objectfactory></objectfactory>
    <!-- 插件:mybatis的插件,插件可以修改mybatis的内部运行规则 -->
    <plugins>
        <plugin></plugin>
    </plugins>
    <!-- 环境:配置mybatis的环境 -->
    <environments>
        <!-- 环境变量:可以配置多个环境变量,比如使用多数据源时,就需要配置多个环境变量 -->
        <environment>
            <!-- 事务管理器 -->
            <transactionmanager></transactionmanager>
            <!-- 数据源 配置连接我的数据库-->
            <datasource>
                <property></property>
                <property></property>
                <property></property>
                <property></property>
            </datasource>
        </environment>
    </environments>
    <!-- 数据库厂商标识 -->
    <databaseidprovider></databaseidprovider>
    <!-- 映射器:指定映射文件或者映射类 -->
    <mappers>
        <mapper></mapper>
    </mappers></configuration>
ログイン後にコピー

ページング

データ アクセス量の削減

limt はページングを実装します
SQL ステートメント: select * from table name limt 0,5;

    0 : データの開始位置
  • 5: データ長

#最初のタイプ: Mybatis を使用# 1 インターフェース

  List<user> getUserByLimit(Map<string> map);</string></user>
ログイン後にコピー
2mapeer.xml

   <select>
        select *
        from mybatis.user
        limit ${starIndex},${pageSize}    </select>
ログイン後にコピー
2-1 結果セットのマッピング

<resultmap>
        <result></result>
    </resultmap>
ログイン後にコピー
3 テスト

 @Test
    public void getUserByLimitTest() {
        SqlSession sqlSession = MyBatisUtils.getSqlSession ();
        UserMapper mapper = sqlSession.getMapper (UserMapper.class);
        HashMap hashMap = new HashMap<string> ();
        hashMap.put ("starIndex", 1);
        hashMap.put ("pageSize", 2);
        List userByLimit = mapper.getUserByLimit (hashMap);
        for (Object o : userByLimit) {
            System.out.println (o);
        }

        sqlSession.close ();
    }</string>
ログイン後にコピー

2 番目: RowBounds メソッドを使用します 1. インターフェイス
List getUserList();
2. インターフェイス

<select>
        select *
        from mybatis.user    </select>
ログイン後にコピー
を実装します。 3. テスト:

 /**
     * 测试使用RowBounds实现分页
     */@Test
    public void getUserByLimitRowBoundsTest() {
        SqlSession sqlSession = MyBatisUtils.getSqlSession ();
        RowBounds rowBounds = new RowBounds (0, 2);
        List<user> userList = sqlSession.selectList ("com.kuang.w.dao.UserMapper.getUserList", null, rowBounds);
        for (User user : userList) {
            System.out.println (user);
        }
        //关闭
        sqlSession.close ();
    }</user>
ログイン後にコピー

3 番目の方法: Mybatis のページング プラグイン pageHeIper を使用します。
Mybatis の基本を理解する

sql 多対 1 処理

データベース:

Mybatis の基本を理解する
pojoデータベース内の Teacher-table テーブルはエンティティ クラス Teacher

package com.kuang.w.pojo;

import lombok.Data;

/**
 * @author W
 */
@Data
public class Teacher {
    private int tId;
    private String tName;

}
ログイン後にコピー
に対応します。データベース内の user テーブルはエンティティ クラス Student

package com.kuang.w.pojo;import lombok.Data;/**
 * @author W
 */@Datapublic class Student {
    private int id;
    private int tid;
    private String name;
    private String password;
    private Teacher teacher;}
ログイン後にコピー
1.Interface

   List<student> getStudentList();</student>
ログイン後にコピー
2 に対応します。 .xml 設定実装インターフェイス

  <!-- 多对一查询
    1 子查询 mysql 通过一个表里是数据   与另一个表的一个数据相的情况下 查询另一个的数据 一起显示
  -->
    <select>
        select *
        from mybatis.user;    </select>
    <resultmap>
        <!--  复杂属性 对象用 :association 集合用:collection-->
        <!--column 数据库中的字段 property 实体类中的属性-->
        <result></result>
        <result></result>
        <result></result>
        <!--javaType	一个 Java 类的全限定名
        ,或一个类型别名(关于内置的类型别名,可以参考上面的表格)。
        如果你映射到一个 JavaBean,MyBatis 通常可以推断类型。
        然而,如果你映射到的是 HashMap,
        那么你应该明确地指定 javaType 来保证行为与期望的相一致。-->
        <association></association>
    </resultmap>
    <select>
        select *
        from mybatis.teacher_table
        where tid = #{id};    </select>
ログイン後にコピー
 <!--2 多表联查-->
    <select>
        select u.id       uid,
               u.name     uname,
               u.password upassword,
               u.tid      utid,
               t.tname
        from mybatis.user u,
             mybatis.teacher_table t
        where t.tid = u.tid;    </select>
     <!-- 映射-->
    <resultmap>
        <result></result>
        <result></result>
        <result></result>
        <result></result>
        <association>
            <result></result>
        </association>
    </resultmap>
ログイン後にコピー
mybatis-config.xm 設定

<?xml  version="1.0" encoding="UTF8" ?>nbsp;configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>
    <properties></properties>
    <settings>
        <setting></setting>
    </settings>
    <typealiases>
        <typealias></typealias>
        <typealias></typealias>
    </typealiases>

    <environments>
        <environment>
            <transactionmanager></transactionmanager>
            <datasource>
                <property></property>
                <property></property>
                <property></property>
                <property></property>
            </datasource>
        </environment>
    </environments>
    <mappers>
        <!--   <mapper resource="com/kuang/w/dao/TeacherMapper.xml"></mapper>
           <mapper resource="com/kuang/w/dao/StudentMapper.xml"></mapper>-->
        <mapper></mapper>
        <mapper></mapper>
    </mappers></configuration>
ログイン後にコピー
3 Test

 @Test
    public void getStudentListTest() {
        SqlSession sqlSession = MyBatisUtils.getSqlSession ();
        StudentMapper mapper = sqlSession.getMapper (StudentMapper.class);


        List<student> studentList = mapper.getStudentList ();
        for (Student student : studentList) {
            System.out.println (student);
        }

        sqlSession.commit ();
        sqlSession.close ();
    }</student>
ログイン後にコピー

SQL 1 対多処理

データ テーブル構造に対応するエンティティ クラスは変更されません

最初の方法: 複数テーブルの結合クエリ

1 インターフェイス

    List<teacher> getTeacher(int tid);</teacher>
ログイン後にコピー
2.1 XML 実装インターフェイス

  <select>
        select t.tid, t.tname, u.id, u.name, u.password
        from mybatis.user u,
             mybatis.teacher_table t
        where t.tid = u.tid
          and t.tid = #{tid};    </select>
ログイン後にコピー
2.2 マッピング設定

<resultmap>
        <result></result>
        <result></result>
        <!--  复杂属性 对象用 :association 集合用:collection-->
        <collection>
            <!--javaType 指定属性类型 一个 Java 类的全限定名-->
            <result></result>
            <result></result>
            <result></result>
            <result></result>
        </collection>
    </resultmap>
ログイン後にコピー
3Test

 /*测试一对多*/
    @Test
    public void getTeacherTest2() {
        SqlSession sqlSession = MyBatisUtils.getSqlSession ();
        TeacherMapper mapper = sqlSession.getMapper (TeacherMapper.class);
        List<teacher> teacher = mapper.getTeacher (1);
        for (Teacher teacher1 : teacher) {
            System.out.println (teacher1);
        }

		//提交事务   架子  这里可以不要
        sqlSession.commit ();
        // 关闭
        sqlSession.close ();
    }</teacher>
ログイン後にコピー
Result

com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.kuang.w.dao.myTest,getTeacherTest2
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.Opening JDBC Connection
Created connection 164974746.Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@9d5509a]==>  Preparing: select t.tid, t.tname, u.id, u.name, u.password from mybatis.user u, mybatis.teacher_table t where t.tid = u.tid and t.tid = ?; ==> Parameters: 1(Integer)2 番目の方法: サブクエリ

1Interface

    List<teacher> getTeacher(int tid);</teacher>
ログイン後にコピー
2 実装Interface

 <!--第二种方式: 子查询-->
    <select>
        select *
        from mybatis.teacher_table
        where tid = #{tid};    </select>
    <resultmap>
        <!--  复杂属性 对象用 :association 集合用:collection
        我们需要单独处理对象: association 集合: collection
        javaType=""指定属性的类型!
        集合中的泛型信息,我们使用ofType 获取
        -->
        <result></result>
        <result></result>
        <collection>
        </collection>
    </resultmap>
    <select>
        select *
        from mybatis.user
        where tid = #{tid};    </select>
ログイン後にコピー
3上記と同じテストを行います

。 。 。 。

関連する無料学習の推奨事項: mysql データベース(ビデオ)

以上がMybatis の基本を理解するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

DockerでのMySQLメモリの使用を減らします DockerでのMySQLメモリの使用を減らします Mar 04, 2025 pm 03:52 PM

この記事では、DockerのMySQLメモリ使用量を最適化することを調査します。 監視手法(Docker統計、パフォーマンススキーマ、外部ツール)および構成戦略について説明します。 これらには、Dockerメモリの制限、スワッピング、およびcgroupsが含まれます

mysqlの問題を解決する方法共有ライブラリを開くことができません mysqlの問題を解決する方法共有ライブラリを開くことができません Mar 04, 2025 pm 04:01 PM

この記事では、MySQLの「共有ライブラリを開くことができない」エラーについて説明します。 この問題は、必要な共有ライブラリ(.so/.dllファイル)を見つけることができないMySQLの障害に起因しています。ソリューションには、システムのパッケージMを介してライブラリのインストールを確認することが含まれます。

Alter Tableステートメントを使用してMySQLのテーブルをどのように変更しますか? Alter Tableステートメントを使用してMySQLのテーブルをどのように変更しますか? Mar 19, 2025 pm 03:51 PM

この記事では、MySQLのAlter Tableステートメントを使用して、列の追加/ドロップ、テーブル/列の名前の変更、列データ型の変更など、テーブルを変更することについて説明します。

Linuxでmysqlを実行します(phpmyAdminを使用してポッドマンコンテナを使用して/なし) Linuxでmysqlを実行します(phpmyAdminを使用してポッドマンコンテナを使用して/なし) Mar 04, 2025 pm 03:54 PM

この記事では、PHPMyAdminの有無にかかわらず、LinuxにMySQLを直接インストールするのとPodmanコンテナを使用します。 それは、各方法のインストール手順を詳述し、孤立、携帯性、再現性におけるポッドマンの利点を強調しますが、

sqliteとは何ですか?包括的な概要 sqliteとは何ですか?包括的な概要 Mar 04, 2025 pm 03:55 PM

この記事では、自己完結型のサーバーレスリレーショナルデータベースであるSQLiteの包括的な概要を説明します。 SQLiteの利点(シンプルさ、移植性、使いやすさ)と短所(同時性の制限、スケーラビリティの課題)を詳しく説明しています。 c

MACOSで複数のMySQLバージョンを実行する:ステップバイステップガイド MACOSで複数のMySQLバージョンを実行する:ステップバイステップガイド Mar 04, 2025 pm 03:49 PM

このガイドは、HomeBrewを使用してMacOSに複数のMySQLバージョンをインストールおよび管理することを示しています。 Homebrewを使用して設置を分離し、紛争を防ぐことを強調しています。 この記事では、インストール、開始/停止サービス、および最高のPRAを詳述しています

MySQL接続用のSSL/TLS暗号化を構成するにはどうすればよいですか? MySQL接続用のSSL/TLS暗号化を構成するにはどうすればよいですか? Mar 18, 2025 pm 12:01 PM

記事では、証明書の生成と検証を含むMySQL用のSSL/TLS暗号化の構成について説明します。主な問題は、セルフ署名証明書のセキュリティへの影響を使用することです。[文字カウント:159]

人気のあるMySQL GUIツール(MySQL Workbench、PhpMyAdminなど)は何ですか? 人気のあるMySQL GUIツール(MySQL Workbench、PhpMyAdminなど)は何ですか? Mar 21, 2025 pm 06:28 PM

記事では、MySQLワークベンチやPHPMyAdminなどの人気のあるMySQL GUIツールについて説明し、初心者と上級ユーザーの機能と適合性を比較します。[159文字]

See all articles