首页 > 其他分享 >Mybatis使用

Mybatis使用

时间:2023-04-26 23:11:20浏览次数:29  
标签:uid 元素 public uname 使用 Mybatis id select

1.  <insert>元素

  很多时候,执行插入操作后,需要获取插入成功的数据生成的主键值,不同类型数据库获取主键值的方式不同,下面分别对支持主键自动增长的数据库获取主键值和不支持主键自动增长的数据库获取主键值的方式进行介绍。

  如果使用的数据库支持主键自动增长(如MySQL和SQL Server),那么可以通过keyProperty属性指定类的某个属性接收主键返回值(通常会设置到id属性上),然后将useGeneratedKeys的属性值设置为true。

<insert id="addUser" parameterType="com.itheima.pojo.User"
	keyProperty="uid" useGeneratedKeys="true" >
   	insert into 	users(uid,uname,uage)values(#{uid},#{uname},#{uage})
</insert>

  使用不支持主键自动增长的数据库获取主键值。

    <insert id="insertUser" parameterType="com.itheima.pojo.User" >
        <selectKey keyProperty="uid" order="AFTER" resultType="Integer">
            SELECT LAST_INSERT_ID()
        </selectKey>
            insert into users(uid, uname, uage) values (#{uid}, #{uname}, #{uage})
    </insert>

  如果设置为BEFORE,那么它会首先执行<selectKey>元素中的配置来设置主键,然后执行插入语句;如果设置为AFTER,那么它先执行插入语句,然后执行<selectKey>元素中的配置内容。

2. <update>元素的更新使用

    <update>元素用于映射更新语句,它可以更新数据库中的数据。在执行完元素中定义的SQL语句后,会返回更新的记录数量。使用<update>元素执行更新操作非常简单,示例代码如下:

<!—更新操作 -->

<update id="updateUser" parameterType="com.itheima.pojo.User">
    update users set uname= #{uname},uage = #{uage} where uid = #{uid}
</update>

 

3. <delete>元素的删除使用 

  <delete>元素用于映射删除语句,在执行完<delete>元素中的SQL语句之后,会返回删除的记录数量。使用<delete>元素执行删除操作非常简单,示例代码如下所示: 

    <delete id="deleteUser" parameterType="Integer">
        delete from users where uid=#{uid}
    </delete>

4. <sql>元素的作用 

  在一个映射文件中,通常需要定义多条SQL语句,这些SQL语句的组成可能有一部分是相同的(如多条select语句中都查询相同的id、username字段),如果每一个SQL语句都重写一遍相同的部分,势必会增加代码量。针对此问题,可以在映射文件中使用MyBatis所提供的<sql>元素,将这些SQL语句中相同的组成部分抽取出来,然后在需要的地方引用。 <sql>元素的作用是定义可重用的SQL代码片段,它可以被包含在其他语句中。<sql>元素可以被静态地(在加载参数时)参数化,<sql>元素不同的属性值通过包含的对象发生变化。

<!--定义要查询的表 -->
    <sql id="someInclude">
        from users
    </sql>
    <!--定义查询列 -->
    <sql id="userColumns">uid,uname,uage</sql>
    <!--根据客户id查询客户信息 -->
    <select id="findUserById" parameterType="Integer"
            resultType="com.itheima.pojo.User">
        select
        <include refid="userColumns"/>
        <include refid="someInclude">
        </include>
        where uid = #{uid}
 </select>

进阶用法
通过property标签动态传参,使用时用 ${PROPERTY_NAME}
在 if 等标签和代码段中都可使用

    <select id="selectById" resultMap="BaseResultMap">
        select
            my.*
        FROM
            sys_user my
        <include refid="test">
            <property name="testVal" value="1"/>
        </include>
    </select>

    <sql id="test">
        <if test="${testVal} != null">
            WHERE my.id = ${testVal}
        </if>
    </sql>
	-- 执行结果:select my.* FROM sys_user my WHERE my.id = 1 

注意:
mybatis中有两种传入动态参数的方式:#{}和${}
#{} 占位符:对传入的参数会做预编译,也就是会当做字符串来处理

${} 拼接符:对传入的参数不会做任何的处理,也就是说传递什么就是什么
举例:
1. select * from sys_user where id = #{id} and name = #{name}
最后执行的sql:select * from sys_user where id = ‘1’ and name = ‘zhangsan’
2. select * from sys_user where id = ${id} and name = ${name}
最后执行的sql:select * from sys_user where id = 1 and name = zhangsan (这里zhangsan没有单引号,因此会报错。如果需要加单引号,则需要手动在传参时传入。)

改进版本:

 <!--定义要查询的表 -->
    <sql id="someInclude">
        from ${include_target}
    </sql>
    <!--定义查询列 -->
    <sql id="userColumns">uid,uname,uage</sql>
    <!--根据客户id查询客户信息 -->
    <select id="findUserById" parameterType="Integer"
            resultType="com.itheima.pojo.User">
        select
        <include refid="userColumns"/>
        <include refid="someInclude">
            <property name="include_target" value="users"/>
        </include>
        where uid = #{uid}
    </select>

5. <resultMap>元素的作用  

  <resultMap>元素表示结果映射集,是MyBatis中最重要也是功能最强大的元素。<resultMap>元素主要作用是定义映射规则、更新级联以及定义类型转化器等。 数据表中的列和需要返回的对象的属性可能不会完全一致,这种情况下MyBatis不会自动赋值,这时就需要使用<resultMap>元素进行结果集映射。例如将User中的年龄字段改为如下:

package com.itheima.pojo;

public class User {
    private int uid;             //用户id
    private String uname;       //用户姓名
    private int myAge;            //用户年龄


    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public int getMyAge() {
        return myAge;
    }

    public void setMyAge(int myAge) {
        this.myAge = myAge;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", uname='" + uname + '\'' +
                ", myAge=" + myAge +
                '}';
    }
} 

在xml文件中写入如下代码

    <resultMap type="com.itheima.pojo.User" id="userMap">
            <id property="uid" column="uid"/>
            <result property="uname" column="uname"/>
            <result property="myAge" column="uage"/>
    </resultMap>
    <select id="findAllStudent" resultMap="userMap">
            select * from users
    </select>


    <select id="findById" parameterType="int"
            resultType="com.itheima.pojo.User">
        select *
        from users
        where uid = #{id}
    </select>

创建测试类MyBatisTest,在测试类中,编写测试方法findAllStudentTest(),用于测试<resultMap>元素实现查询结果的映射。

public class UserTest {
    @Test
    public void userFindByIdTest() {
        //读取文件名
        String resources = "mybatis-config.xml";
        //创建流
        Reader reader = null;
        try {
            //读取mybatis-config.xml文件内容到reader对象中
            reader = Resources.getResourceAsReader(resources);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //初始化mybatis数据库,创建SqlSessionFactory类的实例
        SqlSessionFactory sqlMapper = new
                SqlSessionFactoryBuilder().build(reader);
        //创建SqlSession实例
        SqlSession session = sqlMapper.openSession();

        List<User> list = session.selectList("findAllStudent");
        for (User tmpUser : list) {
            System.out.println(tmpUser.toString());
        }

        User user2 = session.selectOne("findById", 2);
        System.out.println(user2.toString());
        //关闭session
        session.close();
    }
}

 

 

标签:uid,元素,public,uname,使用,Mybatis,id,select
From: https://www.cnblogs.com/helloworldcode/p/17357688.html

相关文章

  • 小知识:使用errorstack定位特定问题
    有客户遇到ORA-2289的报错,同事协助去现场排查,我帮着远程共同check下。客户只是应用端报出的错误,为了进一步定位,服务端需要开errorstack协助定位具体问题。下面就以这个ORA-2289为例,示范下errorstack的使用方法。--开启errorstackaltersystemsetevents'2289tracenameerr......
  • 使用eclipsefdn/hugo-node容器构建hugo静态站点
    eclipsefdn/hugo-node容器是一个基于Node.js和Hugo的Docker容器,用于构建和部署静态网站。它包含了Hugo和Node.js的环境,可以方便地进行网站的开发、构建和部署。使用eclipsefdn/hugo-node容器可以简化网站开发和部署的流程,具体步骤如下:安装Docker在使用eclipsefdn/hugo-node容......
  • 在linux中如何读取使用tcpdump命令抓取保存的tcpdump capture file类型的数据文件
    笔者在之前的文章中,说明了如何在linux使用tcpdump命令进行抓包,以及将抓包结果保存到文件具体操作,可以参考:https://www.cnblogs.com/5201351/p/17357444.html如果是使用tcpdump命令,-wxxxxxx.dump这种方式保存的文件,我们可以通过file命令发现其文件类型[root@localhostqq-52......
  • go:函数高级、包的使用、if-else、循环、switch、数组
    目录一、函数高级二、包的使用三、if-else四、循环五、switch六、数组七、作业python实现链表一、函数高级1、函数的参数和返回值都是类型的一部分,函数可以赋值给一个变量,有两种情况:test3函数,接收一个参,参数是函数类型:没有参数没有返回值test3有返回值,返回值是个函数:函数......
  • 明解STM32—GPIO应用设计篇之API函数及配置使用技巧
    一、前言        本篇开始对STM32的GPIO在实际开发设计中的使用配置和技巧进行探讨,可以先去回顾下之前介绍的GPIO的相关理论基础知识包括基本结构,工作模式和寄存器原理。        了解过STM32的GPIO相关的理论知识,这样在应用GPIO开发过程中,能更好的理解GPIO的特......
  • 关于在linux中使用tcpdump命令进行简单的抓包操作
    如果需要在linux操作系统中对网络数据进行抓包,然后进行数据分析,一般使用最多的就是tcpdump命令了这里笔者介绍一下,关于linux下tcpdump命令的简单使用方法,首先是需要在OS中安装tcpdump软件包的(最小化安装的系统中是没有tcpdump的)[root@localhostqq-5201351]#yuminstalltcpd......
  • 明解STM32—GPIO应用设计篇之API函数及配置使用技巧
     一、前言本篇开始对STM32的GPIO在实际开发设计中的使用配置和技巧进行探讨,可以先去回顾下之前介绍的GPIO的相关理论基础知识包括基本结构,工作模式和寄存器原理。了解过STM32的GPIO相关的理论知识,这样在应用GPIO开发过程中,能更好的理解GPIO的特点,应用起来会更加的得心应手。后续将......
  • jsx中使用js表达式
    //在jsx中使用js表达式///通过一个{}展示变量即可vue中使用{{}}展示js表达式//什么是js表达式有结果的importreactDomfrom"react-dom"//函数也是表达式//syntaxError语法错误constsayHi=()=>{return"你好"}constspan=<span>我是一......
  • react的基本使用
    //导入react和react-dom包importreactfrom'react'importreactDomfrom'react-dom'//console.log(react)//console.log(reactDom)//创建react元素//参数1.元素2.属性【没有就写null】3.元素子节点//react创建元素并返回consth1=react.crea......
  • jpa入门(使用hibernate)
    新建工程,加入jar包,如图:User:packagecom.jpa;importjavax.persistence.Column;importjavax.persistence.Entity;importjavax.persistence.GeneratedValue;importjavax.persistence.GenerationType;importjavax.persistence.Id;importjavax.persistence.SequenceGenerat......