Java: MyBatis explained

1. Introduction to MyBatis

What is MyBatis

  • MyBatis is an excellent persistence layer framework used to simplify JDBC development
  • MyBatis was originally an open source project iBatis of Apache. In 2010, the project was moved from the apache software foundation to google code and renamed MyBatis. Migrated to Github in November 2013

persistence layer

  • The layer of code responsible for saving data to the database
  • javaEE three-tier architecture: presentation layer, business layer, persistence layer

frame

  • A framework is a semi-finished software, a set of reusable, universal software basic codes.
  • Building software based on the framework is more efficient, standardized, universal and scalable
2. Quick Start with MyBatis

Building steps

  1. New module
  2. Import jar package
  3. Write User class
  4. Write the configuration file mybatis-config.xml
  5. Modify connection pool information
  6. Write interface
  7. Write mapping file
  8. Write test class

Case presentation

  • Prepare MySQL data
CREATE DATABASE day18;
USE day18;
CREATE TABLE USER (
  id INT PRIMARY KEY AUTO_INCREMENT,
  username VARCHAR(20) NOT NULL,
  birthday DATE,
  sex CHAR(1) DEFAULT '男',
  address VARCHAR(50)
);

INSERT INTO USER VALUES (NULL, '孙悟空','1980-10-24','男','花果山水帘洞');
INSERT INTO USER VALUES (NULL, '白骨精','1992-11-12','女','白虎岭白骨洞');
INSERT INTO USER VALUES (NULL, '猪八戒','1983-05-20','男','福临山云栈洞');
INSERT INTO USER VALUES (NULL, '蜘蛛精','1995-03-22','女','盤丝洞');
  1. New Project

  2. Import jar package

    Import via pom.xml

        <dependencies>
            <!--单元测试-->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
            </dependency>
    
            <!--MySQL驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.46</version>
            </dependency>
    
            <!--MyBatis核心包-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.5</version>
            </dependency>
        </dependencies>
    
  3. Write entity class

    Remember here to be consistent with the database

    /**
     * 封装User表的实体类
     */
    public class User {
          
          
        private Integer id;
        private String username;
        private Date birthday;
        private String sex;
        private String address;
    }
    
  4. Copy mybatis-config.xml to resources

  5. Modify connection pool information

    <?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>
    	<settings>
            <!--在控制台显示SQL语句-->
            <setting name="logImpl" value="STDOUT_LOGGING"/>
        </settings>
    	
        <environments default="development">
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <!--配置连接池需要的参数-->
                    <property name="driver" value="驱动类全名"/>
                    <property name="url" value="数据库url"/>
                    <property name="username" value="数据库账号"/>
                    <property name="password" value="数据库密码"/>
                </dataSource>
            </environment>
        </environments>
    
        <mappers>
            <mapper resource="接口映射文件位置"/>
        </mappers>
    </configuration>
    
  6. Write interface

    The advantage of writing an interface is to unify the method of managing the database

    /**
     * xxxMapper就说对应xxx表的数据操作
     */
    public interface UserMapper {
          
          
    
        // 1、查询User表的所有数据
        List<User> selectAll();
    
    }
    
  7. Write mapping file

    <?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">
    
    <mapper namespace="包名.接口名">
        <select id="方法名" resultType="方法返回值类型">
            SQL语句
        </select>
    </mapper>
    
  8. Write test class

    public class UserTest {
          
          
    
        @Test
        public void test01() throws IOException {
          
          
            //测试框架搭建情况
            //1、标记mybatis的配置环境
            String resource = "mybatis-config.xml";
            //2、加载配置环境的信息
            InputStream inputStream = Resources.getResourceAsStream(resource);
            //3、根据配置信息,生成SqlSessionFactory对象,相当于连接池
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            //4、从连接池获取连接
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //5、获取执行sql语句的对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //6、调用方法执行sql语句
            List<User> users = mapper.selectAll();
    
            sqlSession.close();
    
            for (User user : users) {
          
          
                System.out.println(user);
            }
        }
    }
    
3. MyBatis core configuration file

The top-level structure of the MyBatis core configuration file is as follows

  • configuration
    • properties
    • settings
    • typeAliases (type aliases)
    • typeHandlers(type handler)
    • objectFactory(object factory)
    • plugins
    • environments (environment configuration)
      • environment(environment variable)
        • transactionManager(transaction manager)
        • dataSource(data source)
    • databaseldProvider (database vendor identification)
    • mappers (mapper)

typeAliasesaliases

  • The role of typeAliases: Give aliases to custom entity classes to make the class easier to use.

    1. Configure it in mybatis-config.xml, behind settings
    2. Note that the tags in mybatis-config.xml have a standardized ranking order. If the order is incorrect, the configuration tag will report an error.
  • method one:

    This method is to configure an alias for a single class, but the disadvantage is that if multiple classes are configured, a lot of aliases need to be written.

    <!--
    typeAliases 给类名起别名
    typeAlias 给单个类配置别名
    type:原本包名+类名
    alias:起的别名
    -->
    <typeAliases>
          <typeAlias type="org.example.pojo.User" alias="User"></typeAlias   </typeAliases>
              
              
    
  • Method two:

    Configuring through package scanning has the advantage that all classes in this directory can be used.

        <typeAliases>
            <package name="org.example.pojo"/>
        </typeAliases>
    

mapper packet scanning configuration

Since the class name can be scanned, so can our mapper file.

If the Mapper interface name and the SQL mapping file have the same name and are in the same directory, you can use package scanning to simplify the loading of the SQL mapping file.

  1. Configure in mybatis-config.xml
    <mappers>
        <package name="org.example.mapper"/>
    </mappers>

image-20231106183801618

Supongo que te gusta

Origin blog.csdn.net/weixin_53961667/article/details/134252530
Recomendado
Clasificación