Mybatis parameter transfer--Mybatis quick start nanny level tutorial (3)


foreword

In order to consolidate the knowledge learned, the author tried to start publishing some blogs of learning notes for future review. Of course, it would be great if it could help some newcomers learn new technologies. The author is a piece of food. If there are any mistakes in the records in the article, readers and friends are welcome to criticize and correct.
(The reference source code of the blog and the source code of the learning video linked at the end of the article can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

Six, mybatis parameter transfer

1. Coding environment preparation (aided learning)

(You can find the relevant code in the re_mb_demon module of the personal homepage mybatis source code)

  1. import coordinates
<!--mybatis 依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.13</version>
        </dependency>

        <!--mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.32</version>
        </dependency>

        <!--junit 单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <!-- 添加slf4j日志api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.5</version>
        </dependency>
        
        <!-- 添加logback-classic依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        
        <!-- 添加logback-core依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>

  1. Design and create database table tb_user
create database mybatis;
use mybatis;

drop table if exists tb_user;

create table tb_user(
	id int primary key auto_increment,
	username varchar(20),
	password varchar(20),
	gender char(1),
	addr varchar(30)
);

INSERT INTO tb_user VALUES (1, 'zhangsan', '123', '', '北京');
INSERT INTO tb_user VALUES (2, '李四', '234', '女', '天津');
INSERT INTO tb_user VALUES (3, '王五', '11', '男', '西安');

insert image description here

  1. mybatis core configuration file mybatis-config
<?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>

    <typeAliases>
        <package name="org.example.pojo"/>
    </typeAliases>
    
    <!--
    environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
    -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--数据库连接信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--Mapper代理方式-->
        <package name="org.example.mapper"/>
    </mappers>

</configuration>
  1. The corresponding entity class User
//此处省略getter、setter和toString方法
public class User {
    
    
    private Integer id;
    private String username;
    private String password;
    private String gender;
    private String addr;

  1. Mapper mapping interface UserMapper
public interface UserMapper {
    
    
    
}

  1. Mapper agent core configuration file UserMaper.xml
<?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:名称空间,用于进一步区分-->
<mapper namespace="org.example.mapper.UserMapper">


</mapper>
  1. Log configuration file logback.xml (assistant understanding)
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!--
        CONSOLE :表示当前的日志信息是可以输出到控制台的。
    -->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%level]  %cyan([%thread]) %boldGreen(%logger{
    
    15}) - %msg %n</pattern>
        </encoder>
    </appender>

    <logger name="com.itheima" level="DEBUG" additivity="false">
        <appender-ref ref="Console"/>
    </logger>


    <!--

      level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF
     , 默认debug
      <root>可以包含零个或多个<appender-ref>元素,标识这个输出位置将会被本日志级别控制。
      -->
    <root level="DEBUG">
        <appender-ref ref="Console"/>
    </root>
</configuration>
  1. Mock test class UserMapperTest
public class UserMapperTest {
    
    

}

  1. File structure preview

insert image description here

2. Pass multiple parameters

  1. Mybatis encapsulates multiple parameter parsing

When the dao layer method needs multiple parameters, if the @Param annotation of mybatis is not used, the method is called directly. When Mybatis parses the XML file, the parameter name will be parsed into arg1, arg0..., param1, param2..., which can be encapsulated as a Map collection using
 @ Param annotation, replace the default arg key name in the Map collection
 insert image description here
insert image description here

  1. overview

MyBatis provides developers with an annotation **@Param** (org.apache.ibatis.annotations.Param), which can be used to define the parameter name of the mapper. Using it can get better readability. This time needs To modify the code of the mapping file, there is no need to give the parameterType attribute at this time, just let MyBatis automatically explore, which greatly improves the readability and is convenient for users, but this will cause a trouble. If the SQL is complex and has more than 10 parameters, then the number of parameters of the interface method will be too many, and it is not easy to use, but don't worry, MyBatis also provides the form of passing Java Beans.

  1. Annotation passing multiple parameters general format
public List<Role> findRolesByAnnotation(@Param("roleName") String rolename, @Param("note") String note);
<select id="findRolesByAnnotation" resultType="role">
    select id, role_name as roleName, note from t_role where role_name like concat('%', #{
    
    roleName}, '%') and note like concat('%', #{
    
    note}, '%')
</select>
  1. Practical example
  • Write Mapper mapping interface UserMapper
    User select(@Param("username") String username, @Param("password")String password);

  • Write the Mapper proxy core configuration file UserMaper.xml (sql statement)
    <select id="select" resultType="org.example.pojo.User">
        select *
        from tb_user
        where
            username = #{
    
    username}
          and password = #{
    
    password}
    </select>
  • Write a mock test class UserMapperTest
 @Test
    public void testSelect() throws IOException {
    
    
        //1. 获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //3. 获取Mapper接口的代理对象
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

        //4. 执行方法
        String username = "zhangsan";
        String password = "123";

        User user = userMapper.select(username,password);

        System.out.println(user);

        //5. 释放资源
        sqlSession.close();
    }
  • operation result

insert image description here

3. Pass a single parameter

  1. POJO type: used directly, the attribute name is consistent with the parameter placeholder name
  • Example of interface function
   void add(Brand brand);
  • Example of mock test class object encapsulation
 //接收参数
 int status = 1;
 String companyName = "波导手机";
 String brandName = "波导";
 String description = "手机中的战斗机";
 int ordered = 100;

 //封装对象
 Brand brand = new Brand();
 brand.setStatus(status);
 brand.setCompanyName(companyName);
 brand.setBrandName(brandName);
 brand.setDescription(description);
 brand.setOrdered(ordered);
  • sql statement example
<insert id="add" useGeneratedKeys="true" keyProperty="id">
    insert into tb_brand (brand_name, company_name, ordered, description, status)
    values (#{
    
    brandName}, #{
    
    companyName}, #{
    
    ordered}, #{
    
    description}, #{
    
    status});
</insert>
  1. Map collection: used directly, the key name is consistent with the parameter placeholder name
  • Example of interface function
 List<Brand> selectByCondition(Map map);
  • Example of Map encapsulation
 //接收参数
 int status = 1;
 String companyName = "华为";
 String brandName = "华为";

 // 处理参数
 companyName = "%" + companyName + "%";
 brandName = "%" + brandName + "%";

 Map map = new HashMap();
 map.put("status" , status);
 map.put("companyName", companyName);
 map.put("brandName" , brandName);
  • sql statement example
 <select id="selectByCondition" resultMap="brandResultMap">
     select *
     from tb_brand
     where status = #{
    
    status}
       and company_name like #{
    
    companyName}
       and brand_name like #{
    
    brandName}
 </select>
  1. Collection: encapsulated as a Map collection, you can use the @Param annotation to replace the default arg key name in the Map collection
    map.put("arg0", collection collection);
    map.put("collection", collection collection);

  2. List: encapsulated as a Map collection, you can use the @Param annotation to replace the default arg key name in the Map collection
    map.put("arg0", list collection);
    map.put("collection", list collection);
    map.put( "list", list collection);

  3. Array: encapsulated as a Map collection, you can use the @Param annotation to replace the default arg key name in the Map collection
    map.put("arg0", array);
    map.put("array", array);

  4. Other types: use directly (${any value})

  • Example of interface function
 User selectById(int id);
  • sql statement example
<select id="selectById" resultType="user">
    select *
    from tb_User where id = ${
    
    id};
</select>

4. Summary

insert image description here

Reference Websites and Blogs

  1. [ mybatis Chinese website ]
  2. [ mybatis learning video ]

Summarize

Welcome to leave a message, exchange and criticize and correct. If the article is helpful to you or you think the author's writing is not bad, you can click to follow, like, bookmark and support the author. Springboot, maven advanced, WeChat applet, etc. will be updated in the future content study notes.
(The reference source code of the blog and the source code of the learning video linked at the end of the article can be found in the resources on my homepage. If you have any questions during the learning process, please feel free to ask me in the comment area)

Guess you like

Origin blog.csdn.net/HHX_01/article/details/130703540