Home Database Mysql Tutorial Understand the basics of Mybatis

Understand the basics of Mybatis

Jan 22, 2021 am 09:29 AM

Understand the basics of Mybatis

Free learning recommendation: mysql video tutorial

##mybatis

mybatis-config.xml detailed configuration (when configuring, you must delete the redundant attributes and cannot have Chinese characters, otherwise an error will be reported!)

<?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>
Copy after login

Paging

Reduce the amount of data access

limt implements paging
sql statement: select * from table name limt 0,5;

    0: The starting position of the data
  • 5: Data length

The first type: using Mybatis 1 interface

  List<user> getUserByLimit(Map<string> map);</string></user>
Copy after login
2mapeer.xml

   <select>
        select *
        from mybatis.user
        limit ${starIndex},${pageSize}    </select>
Copy after login
2-1 Result set mapping

<resultmap>
        <result></result>
    </resultmap>
Copy after login
3 Test

 @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>
Copy after login

Second: Use RowBounds method 1. Interface
List getUserList();
2. Implement the interface

<select>
        select *
        from mybatis.user    </select>
Copy after login
3. Test:

 /**
     * 测试使用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>
Copy after login

Third method: Use Mybatis’ paging plug-in pageHeIper
Understand the basics of Mybatis

sql Many-to-one processing

Database:

Understand the basics of Mybatis
pojo The teacher-table table in the database corresponds to the entity class Teacher

package com.kuang.w.pojo;

import lombok.Data;

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

}
Copy after login
The user table in the database corresponds to the entity class 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;}
Copy after login
1.Interface

   List<student> getStudentList();</student>
Copy after login
2.xml configuration implementation interface

  <!-- 多对一查询
    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>
Copy after login
 <!--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>
Copy after login
mybatis-config.xm configuration

<?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>
Copy after login
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>
Copy after login

sql one-to-many processing

The entity class corresponding to the data table structure remains unchanged

First way: Multi-table joint query

1 interface

    List<teacher> getTeacher(int tid);</teacher>
Copy after login
2.1 xml implementation interface

  <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>
Copy after login
2.2 Mapping configuration

<resultmap>
        <result></result>
        <result></result>
        <!--  复杂属性 对象用 :association 集合用:collection-->
        <collection>
            <!--javaType 指定属性类型 一个 Java 类的全限定名-->
            <result></result>
            <result></result>
            <result></result>
            <result></result>
        </collection>
    </resultmap>
Copy after login
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>
Copy after login
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)Second way: Subquery

1Interface

    List<teacher> getTeacher(int tid);</teacher>
Copy after login
2 Implement 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>
Copy after login
3Test the same as above

. . . .

Related free learning recommendations: mysql database(Video)

The above is the detailed content of Understand the basics of Mybatis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Reduce the use of MySQL memory in Docker Reduce the use of MySQL memory in Docker Mar 04, 2025 pm 03:52 PM

This article explores optimizing MySQL memory usage in Docker. It discusses monitoring techniques (Docker stats, Performance Schema, external tools) and configuration strategies. These include Docker memory limits, swapping, and cgroups, alongside

How to solve the problem of mysql cannot open shared library How to solve the problem of mysql cannot open shared library Mar 04, 2025 pm 04:01 PM

This article addresses MySQL's "unable to open shared library" error. The issue stems from MySQL's inability to locate necessary shared libraries (.so/.dll files). Solutions involve verifying library installation via the system's package m

How do you alter a table in MySQL using the ALTER TABLE statement? How do you alter a table in MySQL using the ALTER TABLE statement? Mar 19, 2025 pm 03:51 PM

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

Run MySQl in Linux (with/without podman container with phpmyadmin) Run MySQl in Linux (with/without podman container with phpmyadmin) Mar 04, 2025 pm 03:54 PM

This article compares installing MySQL on Linux directly versus using Podman containers, with/without phpMyAdmin. It details installation steps for each method, emphasizing Podman's advantages in isolation, portability, and reproducibility, but also

What is SQLite? Comprehensive overview What is SQLite? Comprehensive overview Mar 04, 2025 pm 03:55 PM

This article provides a comprehensive overview of SQLite, a self-contained, serverless relational database. It details SQLite's advantages (simplicity, portability, ease of use) and disadvantages (concurrency limitations, scalability challenges). C

How do I configure SSL/TLS encryption for MySQL connections? How do I configure SSL/TLS encryption for MySQL connections? Mar 18, 2025 pm 12:01 PM

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

Running multiple MySQL versions on MacOS: A step-by-step guide Running multiple MySQL versions on MacOS: A step-by-step guide Mar 04, 2025 pm 03:49 PM

This guide demonstrates installing and managing multiple MySQL versions on macOS using Homebrew. It emphasizes using Homebrew to isolate installations, preventing conflicts. The article details installation, starting/stopping services, and best pra

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)? Mar 21, 2025 pm 06:28 PM

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

See all articles