MyBatis的学习

一:简介

1.MyBatis是一款优秀的持久层框架,用于简化JDBC开发

2.MyBatis本身Apache的一个开源项目iBatis。2010年这个项目由Apache software foundation迁移到了Google code,并且改名为MyBaits。2013年11月迁移到Github

3.官网:https://mybatis.org/mybatis-3/zh/index.html

·持久层

(1)负责将数据保存到数据库的那一层代码

(2)JavaEE三层框架:表现层、业务层、持久层

·框架

(1)框架就是一个半成品软件,是一套可重用的、通用的、软件基础代码模型

(2)在框架的基础之上构建软件编写更加高效、规范、通用、可扩展

二:对比

1.JDBC的缺点:

①硬编码:(1)注册驱动,获取连接(2)SQL语句

②操作繁琐:(1)手动设置参数(2)手动封装结果集

2.MyBatis简化:

①硬编码-->配置文件

②操作繁琐-->自动完成

MyBatis免除了几乎所有的JDBC代码以及设置参数和获取结果集的工作

三:MyBatis快速入门

package Class;

public class User {
    private int id;
    private String username;
    private String password;
    private String gender;
    private String addr;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", gender='" + gender + '\'' +
                ", addr='" + addr + '\'' +
                '}';
    }
}
<?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="Class.User">
        select * from tb_user;
    </select>
</mapper>
<?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="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载sql映射文件-->
        <mapper resource="UserMappear.xml"/>
    </mappers>
</configuration>
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

/**
 * MyBatis快速入门代码
 */

public class Test1 {

    public static void main(String[] args) throws Exception {
        //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<Object> users = sqlSession.selectList("test.selectAll");

        System.out.println(users);

        //4.释放资源
        sqlSession.close();
    }
}

四:Mapper代理开发

1.目的:

①解决原生方式中的硬编码

②简化后期执行SQL

2.案例:

import java.util.List;
import Class.User;

public interface UserMapper {

    List<User> selectAll();
    
}
<?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="Mapper.UserMapper">
    <select id="selectAll" resultType="Class.User">
        select * from tb_user;
    </select>
</mapper>
import Mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;
import Class.User;
/**
 * Mapper代理
 */

public class Test2 {

    public static void main(String[] args) throws Exception {
        //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.获取UserMapper接口的代理对象
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        //4.执行sql
        List<User> users = mapper.selectAll();
        System.out.println(users);

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

五:MyBatis核心配置

1.MyBatis核心配置文件的顶层结构如下:

2.类型别名(typeAliases)

细节:配置各个标签时,需要遵守前后顺序

<?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="Class"/>
    </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="123456"/>
            </dataSource>
        </environment>

        <environment id="test">
            <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="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载sql映射文件-->
        <mapper resource="Mapper/UserMappear.xml"/>
    </mappers>
</configuration>

六:MyBatis案例

1.1 查询所有:

注意:数据库的表的名称 和 实体类的属性名称 不一样 则不能自动封装数据

解决方法:

①起别名:对不一样的列名起别名,让别名与实体类的属性名一样

*缺点每次查询都要重新定义一下别名

②sql片段

*缺点:不灵活

③resultMap:

1.定义<resultMap>标签

2.在<select>标签中,使用resultMap属性替换resultType属性

<?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="Mapper.BrandMapper">
    <!--数据库的表的名称 和 实体类的属性名称 不一样 则不能自动封装数据
        *起别名:对不一样的列名起别名,让别名与实体类的属性名一样
            *缺点每次查询都要重新定义一下别名
                *sql片段
                    *缺点:不灵活
        *resultMap:
            1.定义<resultMap>标签
            2.在<select>标签中,使用resultMap属性替换resultType属性

    -->
    <!--
        id:唯一标识
        type:映射的类型,支持别名
    -->
    <resultMap id="brandResultMap" type="brand">
        <!--
            id:完成主键字段的映射
            result:
                column:表的别名
                property:实体类的属性名

        -->
        <result column="brand_name" property="brandname" />
        <result column="company_name" property="companyname" />
    </resultMap>
    <select id="selectAll" resultMap="brandResultMap">
        select * from tb_brand;
    </select>
<!--    <sql id="brand_column">-->
<!--        id,brand_name as brandname,company_name as companyname,ordered,description,status-->
<!--    </sql>-->

<!--    <select id="selectAll" resultType="Brand">&ndash;&gt;-->
<!--        select <include refid="brand_column" /> from tb_brand;-->
<!--    </select>-->

<!--    <select id="selectAll" resultType="Brand">-->
<!--        select * from tb_brand;-->
<!--    </select>-->


<!--    <select id="selectAll" resultType="Brand">-->
<!--        select id,brand_name as brandname,company_name as companyname,ordered,description,status from tb_brand;-->
<!--    </select>-->
</mapper>
public class MybatisTest {
    @Test
    public void testSelectAll() throws Exception {
        //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.获取UserMapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行sql
        List<Brand> brands = mapper.selectAll();
        System.out.println(brands);

        //5.释放资源
        sqlSession.close();


    }
}

1.2 查看详情

①参数占位符:

(1)#():执行SQL时,会将#()占位符替换为?,将来自动设置参数值

(2)$():拼SQL。会存在SQL注入问题

(3)使用时机:

*参数传递,都使用#{}

*如果要对表名、列名进行动态设置,只能使用${}进行sql拼接

②parameterType:用于设置参数类型,该参数可以省略

③SQL语句中特殊字符处理:

*转义字符

*<![CDATA [内容]]>

<select id="selectById" resultMap="brandResultMap">
    select * from tb_brand where id = #{id};
</select>
@Test
public void testSelectAll() throws Exception {
    int id = 1;

    //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.获取UserMapper接口的代理对象
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

    //4.执行sql
    Brand brand = mapper.selectById(id);
    System.out.println(brand);

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

1.3条件查询

参数接收:

①散装参数

②对象参数

③map集合参数

/**
    *  条件查询
    *     *参数接收
    *        1.散装参数
    *        2.对象参数
    *        3.map集合参数
    *
    *
    */

//    List<Brand> selectByCondition(@Param("status") int status,@Param("companyname") String companyname,@Param("brandname") String brandname);

//    List<Brand> selectByCondition(Brand brand);

    List<Brand> selectByCondition(Map map);
@Test
    public void testSelectAll() throws Exception {
        //接收参数
        int status = 1;
        String companyname = "华为";
        String brandname = "华为";

        //处理参数
        companyname = "%"+companyname+"%";
        brandname = "%"+brandname+"%";

        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setCompanyname(companyname);
        brand.setBrandname(brandname);

        Map map = new HashMap();
        map.put("status",status);
        map.put("companyname",companyname);
        map.put("brandname",brandname);

        //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.获取UserMapper接口的代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行sql
//          List<Brand> brands = mapper.selectByCondition(status, companyname, brandname);
//          List<Brand> brands = mapper.selectByCondition(brand);
            List<Brand> brands = mapper.selectByCondition(map);

            System.out.println(brands);

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

1.4动态条件查询(SQL语句会随着用户的输入或外部条件的变化而变化,我们称为动态SQL)

(1)多条件动态查询

<select id="selectByCondition" resultMap="brandResultMap">
    <!--select * from tb_brand where status = #{status} and company_name like #{companyname} and brand_name like #{brandname};-->
    select * from tb_brand
    <where>
        <if test="status != null">and status = #{status}</if>
        <if test="companyname != null and companyname != '' ">and company_name like #{companyname}</if>
        <if test="brandname != null and brandname != '' ">and brand_name like #{brandname}</if>
    </where>
</select>

if:用于判断参数是否有值,使用test属性进行条件判断

*存在的问题:第一个条件不需要逻辑运算符

*解决方案:

1)使用恒等式让所有条件格式都一样

2)<where>标签替换where关键字

(2)单条件动态查询

List<Brand> selectBySingle(Brand brand);

<select id="selectBySingle" resultMap="brandResultMap">
    select * from tb_brand
        <where>
            <choose>
                <when test="status != null">
                    status = #{status};
                </when>
                <when test="companyname != null and companyname != ''">
                    company_name like #{companyname};
                </when>
                <when test="brandname != null and brandname != '' ">
                    brand_name like #{brandname};
                </when>
            </choose>
        </where>
</select>

·从多个条件中选择一个

choose(when,otherwise):选择,类似于Java中的switch语句

when相当于case;otherwise相当于default

2.1添加

void add(Brand brand);

<insert id="add">
    insert into tb_brand values (#{id},#{brandname},#{companyname},#{ordered},#{description},#{status})
</insert>
@Test
public void testAdd() throws Exception {
    //接收参数
    int id = 4;
    String companyname = "菠萝";
    String brandname = "菠萝手机";
    int ordered = 1000;
    String description = "美国有苹果,中国有菠萝";
    int status = 1;

    Brand brand = new Brand();
    brand.setStatus(status);
    brand.setCompanyname(companyname);
    brand.setBrandname(brandname);
    brand.setDescription(description);
    brand.setId(id);
    brand.setOrdered(ordered);


    //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(true);

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

    //4.执行sql
    mapper.add(brand);

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

MyBatis事务:

openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit();手动提交事务

openSession(true):可以设置为自动提交事务(关闭事务)

2.2添加-主键返回

在添加数据后需要获取插入数据库数据的主键的值

<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>

返回添加数据的主键

<insert useGeneratedKeys="true" keyProperty="id">

3.1修改全部字段

int update(Brand brand);

<update id="update">
    update tb_brand set brand_name = #{brandname},company_name = #{companyname},ordered = #{ordered},description = #{description},status = #{status}
    where id = #{id}
</update>
@Test
public void testUpdate() throws Exception {
    //接收参数
    String companyname = "菠萝科技无限公司";
    String brandname = "菠萝手机";
    int ordered = 1000;
    String description = "美国有苹果,中国有菠萝手机";
    int status = 1;
    int id = 5;

    Brand brand = new Brand();
    //brand.setStatus(status);
    brand.setCompanyname(companyname);
    //brand.setBrandname(brandname);
    //brand.setDescription(description);
    //brand.setOrdered(ordered);
    brand.setId(id);


    //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(true);

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

    //4.执行sql
    int count = mapper.update(brand);
    System.out.println(count);

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

3.2修改动态字段

<update id="update">
    update tb_brand
        <set>
            <if test="brandname != null and brandname != ''">brand_name = #{brandname},</if>
            <if test="companyname != null and companyname != ''">company_name = #{companyname},</if>
            <if test="ordered != null">ordered = #{ordered},</if>
            <if test="description != null and description != ''">description = #{description},</if>
            <if test="status != null">status = #{status}</if>
        </set>
    where id = #{id}
</update>

4.1单个删除

void deleteById(int id);

<delete id="deleteById">
    delete from tb_brand where id = #{id}
</delete>
@Test
public void testDeleteById() throws Exception {
    //接收参数
    int id = 6;


    //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(true);

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

    //4.执行sql
    mapper.deleteById(id);

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

4.2批量删除

void deleteByIds(@Param("ids")int[] ids);

<delete id="deleteByIds">
    delete from tb_brand where id in <foreach collection="ids" item="id" separator="," open="(" close=")">
    #{id}
</foreach>
</delete>
@Test
public void testDeleteByIds() throws Exception {
    //接收参数
    int[] ids ={7,8,9};


    //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(true);

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

    //4.执行sql
    mapper.deleteByIds(ids);

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

注意:MyBatis会将数组参数,封装为一个Map集合

*默认:array = 数组

*使用@Param注释改变Map集合的默认key的名称

七:参数传递

MyBatis接口方法中可以接受各种各样的参数,MyBatis底层对于这些参数进行不同的封装处理方式

1.单个参数

①POJO类型:直接使用,实体类属性名 和 参数占位符名称一致

②Map集合:直接使用,键名 和 参数占位符名称一致

③Collection:封装为Map集合

④List:封装为Map集合

⑤Array:封装为Map集合

⑥其他类型:直接使用

2.多个参数:封装为Map集合

建议:将来都使用@Param注解来修改Map集合中默认的键名,并使用修改后的名称来获取值,这样可读性更高!

八:注解开发

使用注解开发会比配置文件更加方便

@Select("select * from tb_brand where id = #{id}")
Brand selectById(int id);

·查询:@Select

·添加:@Insert

·修改:@Update

·删除:@Delect

提示:①注解完成简单功能②配置文件完成复杂功能

  • 24
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值