1、MyBatis 如何批量插入?

方式一、打开批量插入的 SqlSession

SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
for (int i = 36; i <= 45; i++) {
    userMapper.insertUser(new User(i, "ConstXiong" + i));
}
sqlSession.commit();
sqlSession.close();

方式二、拼接批量插入的 insert SQL

//Java 代码
List<User> userList = new ArrayList<>();
for (int i = 46; i <= 55; i++) {
    userList.add(new User(i,"ConstXiong" + i));
}
userMapper.insertUserBatch(userList);

<!--Mapper xml 中配置-->
<insert id="insertUserBatch" parameterType="java.util.List">
    insert into user values
    <foreach collection="list" item="item" separator =",">
        (#{item.id}, #{item.name})
    </foreach>
</insert>


完整 Demo:

https://javanav.com/val/2d21b1463f2e4faeaf0def0c49df34a4.html



2、MyBatis 如何获取返回自增主键值?

主键自增,可以在 insert 方法执行完之后把 id 设置到传入的对象的属性

#建表 SQL
create table user(
id int PRIMARY KEY auto_increment,
name varchar(400
)
)
;

<!--Mapper xml 配置-->
<insert id="insertUser" parameterType="constxiong.po.User" useGeneratedKeys="true" keyProperty="id">
    insert into user(namevalues(#{name})
</insert>

//java 代码
for (int i = 0; i < 10; i++
{
    User user = new User(null"constxiong" + i);//这里 user.id = null
    userMapper.insertUser(user);
    System.out.println("id:" + user.getId());//插入数据库后,这里的 user.id 为主键值
}


完整 Demo:

https://javanav.com/val/3ac331d2674b4c108469cce54ae126f3.html



3、Mapper 接口如何传递多个参数?

方式一、接口中传多个参数,在 xml 中使用 #{param0}、#{param1}…

方式二、使用 @param 注解指定名称,在 xml 中使用 #{名称}

方式三、多个参数封装到 Java bean 中

方式四、多个参数指定 key,put 到 Map 中

//方式一
//java
System.out.println("------ selectUserByParamIndex ------");
user = userMapper.selectUserByParamIndex(31"ConstXiong1");
System.out.println(user);
//xml
<select id="selectUserByParamIndex" resultType="constxiong.po.User">
    select * from user where id = #{arg0} and name = #{arg1}
</select>


//方式二
//java
System.out.println("------ selectUserByAnnotation ------");
user = userMapper.selectUserByAnnotation(31"ConstXiong1");
System.out.println(user);
//xml
<select id="selectUserByAnnotation" resultType="constxiong.po.User">
    select * from user where id = #{id} and name = #{name}
</select>


//方式三
//java
System.out.println("------ selectUserByPo ------");
user = userMapper.selectUserByPo(new User(31"ConstXiong1"));
System.out.println(user);
//xml
<select id="selectUserByPo" resultType="constxiong.po.User" parameterType="constxiong.po.User">
    select * from user where id = #{id} and name = #{name}
</select>


//方式四
//java
System.out.println("------ selectUserByMap ------");
Map<String, Object> param = new HashMap<>();
param.put("id"31);
param.put("name""ConstXiong1");
user = userMapper.selectUserByMap(param);
System.out.println(user);
//xml
<select id="selectUserByMap" resultType="constxiong.po.User">
    select * from user where id = #{id} and name = #{name}
</select>


打印值

------ selectUserByParamIndex ------
User{id=31, name='ConstXiong1', mc='null'}
------ selectUserByAnnotation ------
User{id=31, name='ConstXiong1', mc='null'}
------ selectUserByPo ------
User{id=31, name='ConstXiong1', mc='null'}
------ selectUserByMap ------
User{id=31, name='ConstXiong1', mc='null'}



4、MyBatis 中有哪些动态 SQL 标签?它们的作用分别是什么?如何实现的?

9 种动态 SQL 标签:if、choose、when、otherwise、trim、where、set、foreach、bind

1 种注解中使用动态 SQL 标签:script


  • if: 根据条件判断

  • choose、when、otherwise: 组合使用,选择多个条件中的一个

  • where: where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除

  • trim: 定制类似 where 标签的功能

  • set: 用于动态包含需要更新的列,忽略其它不更新的列

  • foreach: 对集合进行遍历

  • bind: 允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文

  • script: 要在带注解的映射器接口类中使用动态 SQL,可以使用 script 元素


官方说明文档:https://mybatis.org/mybatis-3/zh/dynamic-sql.html实现源码的入口在这里 XMLScriptBuilder 类中
protected MixedSqlNode parseDynamicTags(XNode node{
    List<SqlNode> contents = new ArrayList<>();
    NodeList children = node.getNode().getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
      XNode child = node.newXNode(children.item(i));
      if (child.getNode().getNodeType() == Node.CDATA_SECTION_NODE || child.getNode().getNodeType() == Node.TEXT_NODE) {
        ...
      } else if (child.getNode().getNodeType() == Node.ELEMENT_NODE) { // issue #628
        //根据 node 名称获取对应 handler
        String nodeName = child.getNode().getNodeName();
        NodeHandler handler = nodeHandlerMap.get(nodeName);
        if (handler == null) {
          throw new BuilderException("Unknown element <" + nodeName + "> in SQL statement.");
        }
        handler.handleNode(child, contents);
        isDynamic = true;
      }
    }
    return new MixedSqlNode(contents);
  }



5、Mapper XML 映射文件中支持哪些标签?分别什么作用?

  • select: 映射查询语句

  • insert: 映射插入语句

  • updae: 映射更新语句

  • delete: 映射删除语句

  • resultMap: 描述如何从数据库结果集中加载对象,是最复杂也是最强大的元素

  • parameterMap: 老式风格的参数映射,已废弃

  • sql: 定义可被其它语句引用的可重用语句块

  • include: 引入 sql 片段

  • selectKey: 为不支持自增的主键生成策略标签

  • cache: 该命名空间的缓存配置

  • cache-ref: 引用其它命名空间的缓存配置

  • 9 种动态 SQL 标签(见上题)


更多相关文章

  1. java中的编码转化方式都有哪些?(大厂高频面试真题)
  2. 详解第三种创建线程的方式-Callable接口
  3. HashMap的负载因子初始值为什么是0.75?这篇文章以最通俗的方式告
  4. Spring Ioc 实例化 Bean 对象有几种方式?
  5. JDBC原理分析(包括基本的使用方式和面试题汇总)
  6. 队列(静态方式)
  7. 分布式锁不是控制并发幂等的方式

随机推荐

  1. Android开机执行指定shell脚本
  2. 使用Android Studio下载Android Support
  3. Android开发 System.out.println(); 控制
  4. 如何实现对Android设备进行文本的模拟输
  5. 【Android(安卓)电量优化】电量优化 ( 充
  6. 仿微信备注 editext下划线
  7. [Android遊戲] 森林跑跑熊:iOS移植的殺時
  8. Android应用程序目录结构分析
  9. android中使用线程(比如修改textview的tex
  10. Go support for Android