MyBatis总览+入门流程

一、配置环境变量 moven

二、MyBatis

入门步骤

1、引入依赖
2、编写实体 User UserDao

User写字段 get set toString方法

UserDao中定义方法

3、在resorce中写UserMapper
<mapper namespace="com.qcby.dao.UserDao">
    <select id="findAll" resultType="com.qcby.entity.User">
        select * from user
    </select>
</mapper>

mapper标签 写入接口 ,select标签找到id 方法名和 resultType 出参 ,里面写上查询语句

4、创建test类
public class UserTest {

    private InputStream in = null;
    private SqlSession session = null;
    private UserDao mapper = null;

    @Before  //前置通知, 在方法执行之前执行
    public void init() throws IOException {
        //加载主配置文件,目的是为了构建SqlSessionFactory对象
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //通过SqlSessionFactory工厂对象创建SqlSesssion对象
        session = factory.openSession();
        //通过Session创建UserDao接口代理对象
        mapper = session.getMapper(UserDao.class);
    }

    @After  //@After: 后置通知, 在方法执行之后执行 。
    public void destory() throws IOException {
        //释放资源
        session.close();
        in.close();
    }
}
    @Test
    public void findAll() throws IOException {
         List<User> users = mapper.findAll();
        for (User user:users) {
            System.out.println(user.toString());
        }
    }
5.mybatis比jdbc好在哪里

1.和JBDC相比消除了JDBC大量冗余的代码,不需要手动开关连接

2.MyBatis的sql语句在xml文件里面编写,改变sql语句不再需要重新编译

三、MyBatis实现增删改查

写入Mapper标签中

有着 select insert delete update四个标签 每个标签的id对应方法名称,resultType是入参,parameterType是出参,resultMap

<?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.qcby.Dao.UserDao">
    <select id="findAll" resultType="com.qcby.entity.User">
        select * from user
    </select>

    <select id="findById" resultType="com.qcby.entity.User" parameterType="java.lang.Integer">
        select * from user where id = #{id}
    </select>

    <insert id="insert" parameterType="com.qcby.entity.User">
        insert into user(username,birthday,sex,address)
        values(#{username},#{birthday},#{sex},#{address})
    </insert>

    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete>

    <update id="update" parameterType="com.qcby.entity.User">
        update user set username = #{username},birthday = #{birthday},
                sex = #{sex},address = #{address} where id = #{id}
    </update>
    <!--返回主键 :我们的主键需要设置自动递增 -->
    <insert id="insertGetId" parameterType="com.qcby.entity.User">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
        insert into user(username,birthday,sex,address)
        values(#{username},#{birthday},#{sex},#{address})
    </insert>
    <!--${}:拼接 , #{}预编译 -->
    <select id="likeByName" resultType="com.qcby.entity.User" parameterType="java.lang.String">
        select * from user where username like '%${value}%';
    </select>

</mapper>

test测试 获取javabean,mapper.方法输出,和上面的test基本一致

设置mapping层进行映射
<resultMap id="ResultMap" type="com.qcby.entity.User">
    <id column="id" property="id" jdbcType="INTEGER"/>
    <result column="username" property="username" jdbcType="VARCHAR"/>
    <result column="birthday" property="birthday" jdbcType="VARCHAR"/>
    <result column="sex" property="sex" jdbcType="VARCHAR"/>
    <result column="address" property="address" jdbcType="VARCHAR"/>
</resultMap>

<select id="findAlResultMap" resultMap="ResultMap">
    select * from user
</select>
看#{}和${}的输出现象

#{}语句在控制台打印的是?,稍后赋值

${}在控制台将值直接打印出来,直接拼接sql语句可能发生sql注入问题

四、mybatis动态SQL

主要是在mapper中配置的sql语句,在不同情况下用不同的sql语句

1、if
<select id="selectUserByUsernameAndSex" parameterType="com.qcby.entity.User"
        resultType="com.qcby.entity.User">
    select * from user
    <where>
        <if test="username != null">
            username=#{username}
        </if>
        <if test="sex != null">
             and sex=#{sex}
        </if>
    </where>
</select>

使用 where标签 和if标签 ,从第二if标签中加入and,因为编译会自动剔除and

2、set if
<update id="update" parameterType="com.qcby.entity.User">
    update user
    <set>
        <if test="username !=null and username!=''">
            username = #{username} ,
        </if>
        <if test="address != null and address != ''">
             address = #{address}
        </if>
     </set>
     where id = #{id}
</update>

用于update拼接

3、choose when otherwish
<select id="selectUserByChoose" resultType="com.qcby.entity.User"
        parameterType="com.qcby.entity.User">
    select * from user
    <where>
        <choose>
            <when test="id !='' and id != null">
                id=#{id}
            </when>
            <when test="username !='' and username != null">
                and username=#{username}
            </when>
            <otherwise>
                and sex=#{sex}
            </otherwise>
        </choose>
    </where>
</select>

先执行choose中的一个when,如果有一个成立,就不判断后面,如果when都不成立,执行otherwish

4、trim
        <trim prefix="where" prefixOverrides="and | or">
            <if test="username != null">
                and username=#{username}
            </if>
            <if test="sex != null">
                and sex=#{sex}
            </if>
        </trim>

在prefix中写入类型可以变成任意标签

五、mybatis关联映射

假设学生和老师的表是多对一关系,即一个老师教多个学生,每个学生只有一个老师

1、第一种形式:按照查询嵌套处理

查询每个学生对应的老师,分别Student的表,和Teacher where t_id=#{t_id}的表

public class Student {

    private Integer id;
    private String Sname;
    private String sex;
    private Integer age;
    private Integer t_id;
    //这个是重点
    private Teacher teacher;
}
public class Teacher {
    private Integer id;
    private String Tname;
}

创建两个类并写入字段,并为每个字段写set、get、toString方法,其中学生 t_id对应老师的id

<!--    多对一查询:查询每个学生所对应的老师-->
<!--第一种形式:按照查询嵌套处理-->
<!--
    1.查询所有的学生信息
    2.根据查询出来的t_id,寻找对应的老师
 -->
<!--    注意学生实体类当中要有老师类的对象才能实现关联查询-->
<!--  resultMap:返回关联的结果映射-->
<select id = "getStudent"  resultMap="StudentTeacher">
    select * from student;
</select>
<!--结果映射集-->
<resultMap id="StudentTeacher"  type="com.qcby.entity.Student">
    <result property="id" column="id"/>
    <result property="Sname" column="Sname"/>
    <result property="sex" column="sex"/>
    <result property="age" column="age"/>
    <result property="t_id" column="t_id"/>
    <!-- 复杂的属性我们需要单独去处理 对象:association   集合:collection   -->
    <!-- property="teacher" student类当中的关联字段 -->
    <!-- column="t_id" 两个表的关联字段-->
    <!-- javaType="com.javen.model.Teacher" 为复杂属性设置类类型-->
    <!-- select="getTeacher"  :调用下一个查询语句       -->
    <association property="teacher" column="t_id" javaType="com.qcby.entity.Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="com.qcby.entity.Teacher">
    select  * from  teacher where id = #{t_id};    <!-- #{id}; 可以写任何东西,因为会自动匹配 t_id -->
</select>

使用 map进行关联,resultMap中包含result 普通字段使用 result标签 property colum 写,复杂对象使用association标签 ,复杂的property 属性是Student中的字段,column是两个表关联的字段,javaType是全类名,select是调用的下面的select属性

2、第二种形式:按照结果嵌套查询(比较常用)

sql语句,直接查处所需要的表

SELECT  student.id,student.name,teacher.name FROM student  
    LEFT JOIN teacher  on student.t_id = teacher.id  

mapper中的写法

   <!--    按照结果嵌套处理-->
<select id="getStudent1" resultMap="StudentTeacher1">
   SELECT  student.id,student.Sname,teacher.Tname FROM student  LEFT JOIN teacher  on student.t_id = teacher.id
</select>
   <resultMap id="StudentTeacher1" type="com.qcby.entity.Student">
       <result property="id" column="id"/>
       <result property="Sname" column="Sname"/>
       <result property="sex" column="sex"/>
       <result property="age" column="age"/>
       <result property="t_id" column="t_id"/>
       <association property="teacher" javaType="com.qcby.entity.Teacher">
           <result property="id" column="id"/>
           <result property="Tname" column="Tname"/>
       </association>
   </resultMap>

使用map映射 ,resultMap中 写入普通字段 和复杂字段 association,association中写入Teacher类中的字段,javaType为全类名

六、mybatis缓存

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于快速构建基于Spring框架的Java应用程序的开发框架。它简化了Spring应用程序的配置和部署过程,提供了一种快速开发的方式。 MyBatis是一个持久层框架,它可以将Java对象与数据库表进行映射,并提供了灵活的SQL查询和更新操作。MyBatis通过XML或注解的方式来配置SQL语句和映射关系。 Redis是一个开源的内存数据库,它支持多种数据结构(如字符串、哈希、列表、集合、有序集合等),并提供了丰富的操作命令。Redis具有高性能、高可用性和可扩展性的特点,常用于缓存、消息队列、计数器等场景。 MySQL是一个开源的关系型数据库管理系统,它支持多用户、多线程和多表操作。MySQL具有良好的性能和稳定性,并且拥有丰富的功能和工具。 将Spring Boot、MyBatis、Redis和MySQL结合使用可以实现一个完整的Java应用程序。Spring Boot提供了便捷的配置和集成方式,可以轻松地将MyBatis和MySQL集成到应用程序中。同时,通过使用Redis作为缓存,可以提高应用程序的性能和响应速度。 具体来说,可以使用Spring Boot的自动配置功能来集成MyBatis和MySQL。通过配置数据源和MyBatis的Mapper接口,可以实现对数据库的访问和操作。同时,可以使用Redis作为缓存,提高数据的读取速度和响应性能。 总结起来,Spring Boot+MyBatis+Redis+MySQL的组合可以实现一个高性能、可扩展的Java应用程序,提供了方便的开发和部署方式,适用于各种类型的应用场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值