Mybatis对参数的处理

环境配置

项目结构

在这里插入图片描述

导入依赖

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.10</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.projectLombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.26</version>
    </dependency>
</dependencies>

jdbc.properties文件

方便给mybatis配置文件设置值

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/hqyj03?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimeZone=Asia/Shanghai
password=yjg
username=root

mybatis配置文件

常见的配置项

在 MyBatis 的配置文件(通常是 mybatis-config.xml)中,可以配置多个标签来定义 MyBatis 的行为和功能。以下是常见的一些 <configuration> 标签及其含义:

  1. <properties>:用于定义配置文件中使用的属性。
  2. <settings>:用于设置 MyBatis 的全局配置项,如开启缓存、启用自动生成主键等。
  3. <typeAliases>:用于设置类型别名,简化在映射文件中的类型引用。
  4. <typeHandlers>:用于配置类型处理器,用于在 Java 对象和数据库列之间进行类型转换。
  5. <objectFactory>:用于指定创建结果对象的工厂方法。
  6. <plugins>:用于配置插件,可以在 MyBatis 的执行过程中添加额外的功能或扩展。
  7. <environments>:用于配置不同的数据库环境,包括数据源、事务管理器等。
  8. <databaseIdProvider>:用于根据数据库厂商的不同选择不同的语句。
  9. <mappers>:用于注册映射器接口或者映射文件,让 MyBatis 能够找到它们并加载。

添加配置项一

<setting name="mapUnderscoreToCamelCase" value="true"/> 

是 MyBatis 的配置项,用于设置是否将数据库中的下划线命名转换为驼峰命名。
默认情况下,MyBatis 会将数据库中的下划线命名方式(例如user_name)映射到 Java 对象的驼峰命名方式(例如userName)。
如果将value值 设置为 false(默认值),则不会进行自动的下划线到驼峰的转换,需要在映射文件或代码中手动指定对应的字段名称,数据库表字段和 Java 类中的属性名称需要保持一致。

添加配置项二

<setting name="logImpl" value="STDOUT_LOGGING"/> 

是 MyBatis 的配置项,用于设置 MyBatis 的日志输出实现。
在 MyBatis 中,可以通过配置不同的日志输出实现来记录 MyBatis 的运行日志,包括 SQL 语句、参数值、执行时间等信息。
将日志输出到标准输出(控制台)上,方便开发者在控制台中查看日志信息。这是 MyBatis 内置的一个基于 Java 标准库的日志输出实现。
除了 “STDOUT_LOGGING”,MyBatis 还提供了其他的日志输出实现选项,例如:

SLF4J_LOGGING: 将日志输出到 SLF4J(Simple Logging Facade for Java)框架,可以配合各种日志框架(如 Logback、Log4j、Log4j2)使用。

LOG4J2_LOGGING: 将日志输出到 Log4j2 日志框架。	

COMMONS_LOGGING: 将日志输出到 Apache Commons Logging 日志框架。

LOG4J_LOGGING: 将日志输出到 Log4j 1.x 日志框架。

JDK_LOGGING: 将日志输出到 Java 标准库的 java.util.logging 包。


添加配置项三

<!--设置映射类型别名-->
    <typeAliases>
       <!--设置pojo包下的类型别名-->
        <package name="com.yjg.mybatis.pojo"/>
    </typeAliases>

使用 <typeAliases> 元素来设置映射类型别名。

类型别名的作用是为 Java 类型(通常是实体类)指定一个简短的别名,以便在 XML 映射文件中使用这些别名来引用相应的类型。

<package name="com.yjg.mybatis.pojo"/> 表示将 com.yjg.mybatis.pojo 包下的所有类都注册为类型别名。

假设在 com.yjg.mybatis.pojo 包中有一个叫做 User 的类,它的完整类名是 com.yjg.mybatis.pojo.User。通过上述配置,我们可以在 XML 映射文件中使用 <User> 来引用该类,而无需使用完整的类名 com.yjg.mybatis.pojo.User

配置文件完整内容

<?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配置内容时,有顺序限制-->

<configuration>
      <!--读取jdbc.properties配置文件-->
 <properties resource="jdbc.properties"></properties>


<settings>
    <!--配置sql日志打印-->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    <!--下划线驼峰映射stu_name映射stuName-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>


    <!--设置映射类型别名-->
    <typeAliases>
       <!--设置pojo包下的类型别名-->
        <package name="com.yjg.mybatis.pojo"/>
    </typeAliases>

    <!--mybatis环境,default属性指定一个环境-->
    <environments default="development">
        <!--id属性自定义的环境唯一标识符-->
        <environment id="development">
            <!--指定使用jdbc事务管理-->
            <transactionManager type="JDBC"/>
            <!--使用mybatis内部带连接池功能的数据源-->
            <dataSource type="POOLED">
                <!--获取配置驱动-->
                <property name="driver" value="${driver}"/>
                <!--获取配置url-->
                <property name="url" value="${url}"/>
                <!--获取配置账号-->
                <property name="username" value="${username}"/>
                <!--获取配置密码-->
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--映射器,映射器的 XML 映射文件包含了 SQL 代码和映射定义信息-->
    <mappers>
        <mapper resource="com/yjg/mybatis/mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

编写代码

数据库代码

CREATE TABLE `student` (
  `stu_id` int(11) NOT NULL AUTO_INCREMENT,
  `stu_name` varchar(255) DEFAULT NULL,
  `stu_age` varchar(255) DEFAULT NULL,
  `stu_salary` decimal(10,2) DEFAULT NULL,
  `stu_birth` date DEFAULT NULL,
  `create_time` datetime DEFAULT NULL,
  PRIMARY KEY (`stu_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

数据显示
在这里插入图片描述

实体类

import lombok.Data;
import java.util.Date;
@Data
//@Alias 注解是 MyBatis 提供的一个注解,用于为类或接口指定一个别名。
//@Alias("s")
public class Student {
    private Integer stuId;
    private String  stuName;
    private Integer stuAge;
    private Double  stuSalary;
    private Date  stuBirth;
    private Date createTime;
}

接口文件

public interface StudentMapper {
    //插入用户
    int insertStudent();

    //查询全部类型
    List<Student> queryStudent();

    //通过id查询学生,传递单个参数
    Student queryStudentById(Integer id);

   /*
   通过名字和age进行查询
     1.方法中的参数会将存储到map集合中,key值设置为arg0 , arg1.....或者设置为param1, param2. ...
     2.sql语句中是通过#{map的key值}来获取到参数值,例如#{arg0}
     3.可以通过@Param注解更改参数在map中的key
     @Param("name")可以修改名称
   */

    Student queryStudentByNameAndAge(@Param("name") String name,@Param("age") int age);
}

映射文件

<?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="com.yjg.mybatis.mapper.StudentMapper">

    <insert id="insertStudent">
        insert into student values(null, 'zhangsan',18,' 200','2020-01-01 ' , now())
    </insert>


    <select id="queryStudent" parameterType="integer" resultType="Student">
              select * from student;
    </select>

      <!--拿到方法的形参,单个参数,#{id}-->
    <select id="queryStudentById" resultType="Student">
          select * from student where stu_id=#{id}
    </select>

     <!--拿到参数的值,多个参数的时候-->
    <select id="queryStudentByNameAndAge" resultType="student">
          select * from student where stu_name=#{name} and stu_age=#{age};
    </select>

</mapper>

在 MyBatis 中,类型别名是对大小写不敏感的。无论是使用大写、小写或混合大小写,都可以正确地引用对应的实体类。如果使用使用 <typeAliases> 元素来设置映射类型别名。将包名 com.yjg.mybatis.pojo 下的 Student 类设置为类型别名,那么在映射文件中使用 studentStudent 都是可以的,并且都会正确地映射到对应的实体类。

映射文件参数

  1. 使用 #{paramName} 占位符:在 SQL 语句中使用 #{paramName} 占位符来表示参数。当调用映射器接口方法时,MyBatis 将自动解析 SQL 语句,并根据方法参数的名称和注解来匹配占位符和参数,此时MyBatis 使用预编译的方式执行 SQL 语句,将实际的参数值填充到占位符处,并执行查询或更新操作。

  2. 使用 ${paramName} 占位符:在 SQL 语句中使用 ${paramName} 占位符来表示参数。这种方式不会进行预编译,而是直接将参数的值替换到 SQL 语句中。存在 SQL 注入的风险,应谨慎使用。

  3. 使用 @Param 注解:在方法参数上使用 @Param("paramName") 注解来指定参数的名称。在映射文件中可以通过参数名称来引用相应的参数

  4. <select><update><insert><delete> 等操作标签中,可以通过 parameterType 属性来明确指定传入参数的类型。该属性用于告诉 MyBatis 针对具体操作需要接收哪种类型的参数。

测试方法

public class Test1 {
    SqlSession sqlSession;
    @Before
    public void test1() throws Exception{
        InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = builder.build(inputStream);
       sqlSession = build.openSession(true);
    }

     //    添加数据
    @Test
    public void test2(){
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        int i = mapper.insertStudent();
        System.out.println(i);
    }
  
     //    查询所有学生
    @Test
    public void test3(){
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.queryStudent();
        students.forEach(System.out::println);
    }

    //    根据id查询
    @Test
    public void test4(){
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = mapper.queryStudentById(2);
        System.out.println(student);
    }

    //    根据多个参数查询
    @Test
    public void test5(){
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        Student student = mapper.queryStudentByNameAndAge("kun", 18);
        System.out.println(student);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yjg_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值