java周总结_230201_mybatis

mybatis的特点是采用配置文件动态管理sql语句,并含有输入映射,输出映射机制以及数据库连接池配置的持久层框架

mybatis的优点:
简单:易于学习,易于使用,通过文档比较完全的掌握它的设计思路和实现
实用:提供了数据映射功能,提供了对底层数据访问的封装,提供了DAO框架,可以使我们更容易开发和配置
灵活:通过sql基本上可以实现我们不使用数据访问框架可以实现的所有功能,或许更多
功能完整:提供了连接管理,缓存支持,线程支持,分布式事务管理,通过配置关系对象映射等数据访问层需要解决的问题.提供了DAO支持,并在DAO框架中封装了ADO.NET,NHibernate和DataMapper
增强系统的可维护性:将业务逻辑和数据访问逻辑分离,是系统的设计更加清晰,更易维护,更易于单元测试,sql和代码的分离,提高了可维护性

mybatis底层执行原理:
通过核心配置文件和映射文件获取sqlsessionfactory对象,再获得sqlsession对象,继而调用执行器接受传入的参数(hashmap,基本数据类型,pojo),执行sql去数据库查询到结果集封装成hashmap,基本数据类型,pojo

mybatis解决实体类和数据库字段不一致的四种方法:
1.起别名:不一致较少适用
2.开启驼峰映射规则,只能解决_,不能解决不一样的问题
3.使用resultMap手动映射
4.使用HashMap进行封装

在mybatis做持久层,insert语句默认不返回记录的主键值,而是返回插入的记录条数
可以在insert标签加入:
keyProperty:对象中的属性名,必须指定
keyColumn:表中的字段名,不是必须指定(字段是属性一致时不需要)
useGeneratedKeys:激活回填功能,必须指定

这样设置后,假定传入的参数为new Emp(null,"XX","开发",25000),keyProperty指定的就是为null的那个属性,执行完成sql后,该对象的null属性会被回填为数据库中的该字段


使用mapper接口必须具备的几个条件:
mapper的namespace必须和mapper接口一致;
mapper接口的方法名必须和sql定义的id一致;
mapper接口中的方法输入的参数类型必须和sql定义的parameterType一致;
mapper接口中的方法的输出参数类型必须和sql定义的resultType一致


properties标签引入外部文件到核心配置文件中

typeAliases标签为Java类型取别名
扫描包的形式则默认为类型的名字,不区分大小写


mappers标签引入映射器文件

environments标签配置数据库连接环境


select:
传参有两种#{}和${}
两者有很大区别:
#{}是sql语句的预处理参数,之后执行sql中用?代替,使用时不需要关注数据类型,mybatis自动实现数据类型转换,并且可以防止sql注入
    ${}实现的是sql语句的直接拼接,不做数据类型转换,需要自行判断数据类型,不能防止sql注入
    
    在某些情况下必须使用${},例如,在分表存储时,我们从哪张表查询是不确定的,也就是说sql语句不能写死,表名是动态的,查询条件是固定的,这样select * from ${tablename} where id = #{id}
    总结:#{}占位符,用于参数传递
    ${}用于sql拼接

如果使用$的话,会默认将值封装到value中,取值需要${value}

如果需要指定特殊变量的话,需要在接口的方法中使用@param注解,在方法参数之前指定参数封装的变量名,如@Param("id") int id

记住:
#{} 预编译占位符,sql语句中使用?代替;
获取参数时与参数名无关;
防止sql注入

${} sql语句的拼接,需要判断参数类型,做具体处理;获取参数通过${value}获取,如果指定参数名需要通过@Param注解;
不能防止sql注入
    

resultType结果输出的类型有三种:
简单类型:string,long,integer
pojo;
HashMap类型


resultMap是mybatis中最重要最强大的元素,可以用它解决两大问题:
1.pojo属性名和表结构字段名不一致问题
2.完成高级查询,比如一对一,一对多,多对多

动态SQL

if
如果sql语句后面有多个if的话,那么只要满足条件,那么这个条件就会添加到sql中。If的条件是一个and 的关系
只要满足条件,就会将sql语句,拼接在主语句后面


choose,when,otherwise
多选一的场景使用choose , 多选多的场景使用if


where  构建where 关键字,

set  使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号

foreach
foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。

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

    <!--    引入数据源-->
    <properties resource="jdbc.properties"/>

    <settings>
        <!--开启驼峰映射规则-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--    类型别名-->
    <typeAliases>
        <package name="com.sky.pojo"/>
    </typeAliases>

    <!--    数据库环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${data.driver}"/>
                <property name="url" value="${data.url}"/>
                <property name="username" value="${data.username}"/>
                <property name="password" value="${data.password}"/>
            </dataSource>
        </environment>
    </environments>

<!--    映射文件引入-->
    <mappers>
        <package name="com.sky.mapper"/>
    </mappers>

</configuration>
<?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.sky.mapper.UserMapper">
    <insert id="insertUser">
        insert into user (username, pwd, uname)
        values (#{user.username}, #{user.pwd}, #{user.uname})
    </insert>
    <update id="updateUser">
        update user
        set username=#{user.username},
            pwd     = #{user.pwd},
            uname=#{user.uname}
        where uid = #{user.uid}
    </update>

    <delete id="deleteUser">
        delete
        from user
        where uid = #{uid}
    </delete>

    <insert id="addUser" useGeneratedKeys="true" keyColumn="uid" keyProperty="uid">
        INSERT INTO user (username,
        pwd,
        uname)
        VALUES (#{user.username},
        #{user.pwd},
        #{user.uname});
        <selectKey order="BEFORE"></selectKey>
    </insert>


    <!--    编写对应的sql语句,根据sql类型使用什么标签,
            id:唯一标识,一般情况是接口方法名
            resultType:输出结果类型,只能用在查询中,必须的.需要写上全路径
            sql语句执行完成后,一条数据的封装类型
            parameterType:输入类型
    -->

    <!--    要求:实体类的属性必须要和表的列名一摸一样-->
    <select id="getUserById" resultType="user">
        select *
        from user
        where uid = #{uid}
    </select>

    <!--    如果结果映射成hashmap的话,列名为key,结果为value-->
    <select id="getAllUser2" resultType="hashmap">
        select *
        from user
    </select>

    <select id="getAllUser1" resultType="com.sky.pojo.User">
        select *
        from user
    </select>
    <select id="getUserCount" resultType="java.lang.Integer">
        select count(uid)
        from user
    </select>


    <!--手动映射解决列名和实体类属性不一致-->
    <select id="getAllUser" resultMap="userResult">
        select *
        from user
    </select>

    <!--    主键映射
            column:主键的列名
            property:这个主键对应的实体中的属性名
            一般列映射相似
    -->
    <resultMap id="userResult" type="user">
        <id property="uid" column="uid"/>
        <!--仅仅需要映射不一致的列-->
        <result property="pwd" column="password"/>
    </resultMap>

    <select id="getUserByAgeAndAddress" resultType="hashmap">
        select *
        from user
        where age &lt; #{age}
          and address = #{address}
    </select>


    <!--    使用动态SQL实现多条件查询
    where标签是用来构建where关键字的,如果有条件成立的话,则会添加,否则不添加
    if 主要是用来判断条件是否成立,如果条件成立的话,则会将这个条件添加到sql语句后面,每一个if都会判断
    -->
    <select id="getUserByNameLikeAndAgeAndAddress" resultType="com.sky.pojo.User">
        select * from user
        <where>
            <if test="uname != null and uname != ''">
                uname like concat("%",#{uname},"%")
            </if>
            <if test="age != null and age != '' and age != 0">
                and age &lt; #{age}
            </if>
            <if test="address != null and address != ''">
                and address = #{address}
            </if>
        </where>
    </select>


    <select id="getUserOrNameLikeOrAgeOrAddress" resultType="com.sky.pojo.User">
        select * from user
        <where>
            <choose>
                <when test="uname!=null and uname!=''">
                    uname like concat("%",#{uname},"%")
                </when>
                <when test="age != null and age != '' and age != 0">
                    and age &lt; #{age}
                </when>
                <when test="address != null and address != ''">
                    and address = #{address}
                </when>
                <otherwise>
                    1=1
                </otherwise>
            </choose>
        </where>
    </select>


    <!--    批量删除
    collection 集合
    item 每个元素进行迭代时的别名
    index指定一个名字,用于表示迭代过程中的迭代位置
    open表示该语句以什么开始
    close 表示该语句以什么结束
    separator 表示分隔符
    -->
    <delete id="deleteUsers">
        delete from user where uid in
        <foreach collection="ids" item="uid" open="(" close=")" separator=",">
            #{uid}
        </foreach>
    </delete>

    <update id="updateUserDong">
        UPDATE kg20.user
        <set>
            <if test="username!=null and username!=''">
                username=#{username},
            </if>
            <if test="pwd!=null and pwd!=''">
                pwd=#{pwd},
            </if>
            <if test="uname!=null and uname!=''">
                uname=#{uname},
            </if>
            <if test="age!=null and age!='' and age != 0">
                age=#{age},
            </if>
            <if test="address!=null and address!=''">
                address=#{address},
            </if>
            <if test="phone!=null and phone!=''">
                phone=#{phone}
            </if>
        </set>
        WHERE uid = #{uid}
    </update>

</mapper> 


 

<?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.sky.mapper.EmpMapper">

    <!--    crud
            cache 缓存
            resultMap 手动映射结果集
            sql 可被其他语句引用的可重用语句块
            -->
<!--将重复的查询结果字段进行封装,在具体的sql中引入该字段,适合多条sql的结果字段相同的情况-->
    <sql id="empResultCol">
        ename
        ,job,salary,deptno
    </sql>

    <insert id="insertEmp" keyProperty="empno" useGeneratedKeys="true">
        insert into emp (empno,ename,job,salary) values (null,#{ename},#{job},#{salary})
    </insert>

    <delete id="deletEmps">
        delete from emp where empno in
        <foreach collection="empnos" item="empno" open="(" close=")" separator=",">
            #{empno}
        </foreach>
    </delete>

    <!--    根据员工姓名模糊查询-->
    <select id="getEmpByEnameLike" resultType="emp">
        select
        <include refid="empResultCol"/>
        from emp
        where ename like concat("%", #{ename}, "%")
    </select>

    <select id="getEmpByEnameLikeAndSalaryAndBonus" resultType="com.sky.pojo.Emp">
        select * from emp
        <where>
            <if test="ename!=null and ename!=''">
                ename like concat("%",#{ename},"%")
            </if>
            <if test="salary!=null and salary!='' and salary!=0">
                and salary &lt; #{salary}
            </if>
            <if test="bonus!=null and bonus!='' and bonus!=0">
                and bonus &lt; #{bonus}
            </if>
        </where>
    </select>

</mapper>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值