MyBatis入门指南

MyBatis是支持定制SQL,存储过程以及高级映射优秀的持久层框架。

在这里插入图片描述


查询user表中所有数据

  1. 创建user表,添加数据
  2. 导入依赖,创建模块
  3. 编写MyBatis核心配置文件
  4. 编写SQL映射文件
  5. 编写代码
    1. 定义P0J0
    2. 加载核心配置文件,获取SqlSessionFactory对象
    3. 获取SqlSession对象,执行SQL语句
    4. 释放资源

一、创建user

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, '张三', '123', '男', '北京');  
insert into tb_user values (2, '李四', '234', '女', '天津');  
insert into tb_user values (3, '王五', '11', '男', '西安');

创建实体类

public class User {
	private Integer id;
	private String name;
	private String password;
	private char sex;
	private String addr;
}

二、导入依赖

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.16</version>
</dependency>

三、编写MyBatis配置

<!-- mybatis-config.xml -->
<?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>  
<environments default="development">  
    <environment id="development">  
        <transactionManager type="JDBC"/>  
        <dataSource type="POOLED">  
            <!--数据库连接信息-->  
            <property name="driver" value="org.mariadb.jdbc.Driver"/>  
            <property name="url" value="jdbc:mariadb://localhost:3306/mybatis"/>  
            <property name="username" value="root"/>  
            <property name="password" value="20040927"/>  
        </dataSource>        
    </environment>
</environments>  
<mappers>  
    <!--加载SQL映射文件-->  
    <mapper resource="UserMapper.xml"/>  
</mappers>  
</configuration>

四、编写SQL映射文件

<!--UserMapper.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="test">  
    <select id="selectAll" resultType="cn.cangli.todo.pojo.User">  
        select * from tb_user;  
    </select>  
</mapper>

五、编写代码

public class TestUser {  
    @Test  
    public void testUser() throws IOException {  
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory  
        String resource = "mybatis-config.xml";  
        InputStream inputStream = Resources.getResourceAsStream(resource);  
        SqlSessionFactory sqlSessionFactory =  
                new SqlSessionFactoryBuilder().build(inputStream);  
  
        //2.获取SqlSession对象,用他来执行Sql  
        SqlSession sqlSession = sqlSessionFactory.openSession();  
  
        //3.执行Sql  
        List<User> users = sqlSession.selectList("test.selectAll");  
  
        System.out.println(users);  
  
        //4.释放资源  
        sqlSession.close();  
        inputStream.close();  
    }  
}

在这里插入图片描述

  1. SqlSessionFactoryBuilder用于构建SqlSessionFactory对象,每个基于MyBatis的应用都是以SqlSessionFactory为核心的。
  2. 有了SqlSessionFactory,我们就可以从中获得SqlSession实例,每一个SqlSession都代表一个会话,每个会话相互隔离,互不影响。
  3. SqlSession使用完毕要释放资源,使用try(SqlSession session = factory.openSession(true)){}
  4. SqlSessionFactory用完就扔,但是SqlSessionFactory可以留着

传入参数

类似于JDBC中的PreparedStatement,预编译和防止SQL注入

resultTypes属性

传入一个参数,为了防止SQL注入,我们使用#而不是$

<!--namespace名称空间-->  
<mapper namespace="test">  
    <select id="selectUserById" resultType="cn.cangli.todo.pojo.User" parameterType="_int">  
        select * from tb_user where id = #{id};   
    </select>  
</mapper>

不过,MyBatis会做类型推断,因此这里parameterType可以省略

<!--namespace名称空间-->  
<mapper namespace="test">  
    <select id="selectUserById" resultType="cn.cangli.todo.pojo.User">  
        select * from tb_user where id = #{id};   
    </select>  
</mapper>

代码

User user=session.selectOne("selectUserById", 3);

传入两个参数

<select id="selectUserByIdAndAge" resultType="User">
	select * from user where id = #{id} and age = # {age}
</select>

代码

User user = session.selectOne("selectUserByIdAndAge",
		Map.of("id",1,"age",18));

或者

User user = session.selectOne("selectUserByIdAndAge",new Param(1,18));

class Param {
	int id;
	int age;
}

resultMaps属性

假设实体类

class Param {
	int id;
	String userName;
	int age;
}

而数据库中的属性是id、name、age

可能返回结果
User(id=1, username=null, age=18)

为解决这个问题,xml改写

<select id="selectUserByIdAndAge" resultMap="test">
	select * from user where id = #{id} and age = # {age}
</select>

<resultMap id="test" type="User">
	<result column="id" property="id"><!--可省略-->
	<result column="name" property="username">
	<result column="age" property="age"><!--可省略-->
</resultMap>

官方提供了自动映射功能,数据库中的蛇形命名会自动转换为驼峰形式,我们只需要在顶部开启设置

<settings>
	<setting name="nameUnderscoreToCamelCase" value="ture"/>
</settings>
<select id="selectUsersByAge" resultType="User">
	select * from user where age >= #{age}
</select>

推荐阅读

MyBatis配置详解

MyBatis常用方法

MyBatis面向接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值