最近工作中用到了mybatis的Java API方式进行开发,顺便也整理下该功能的用法,接下来会针对基本部分进行学习:

1)Java API处理一对多、多对一的用法

2)增、删、改、查的用法;

3)涉及到类型转化的用法;

4)批量修改、批量查询、批量新增的用法。

Mybatis官网给了具体的文档,但是并没有对以上用法具体介绍,因此在这里整理下,以便以后工作用到时,可以参考。

本章主要对一对多、一对一查询的用法进行学习,下边文章分为以下几个步骤:

1)新建maven,并引入mybatis/mysql/druid包;

2)在mysql中新建mydb,并创建parent,child两张主子表;

3)一对多的用法;

4)多对一的用法。

1)新建maven,并引入mybatis/mysql/druid包;

在idea中新建一个maven module(mybatis-test):

修改pom.xml中jdk版本为1.8。

在pom.xml中引入mybaits/mysql/druid/log相关jar包:

        <!--MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--MySql数据库驱动 -->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>

在项目的/src/main/resources下引入新建一下配置文件:

1)db.properties

#oracle.jdbc.driver.OracleDriver | com.mysql.jdbc.Driver
driver=com.mysql.cj.jdbc.Driver
#jdbc:oracle:thin:@localhost:1521:orcl | jdbc:mysql://localhost:3306/mybatis
url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
name=root
password=123456

注意:

driver配置的com.mysql.cj.jdbc.Driver,在mysql新版本中需要这么配置

2)log.properties

# #define DEBUG priority, R
# log4j.rootLogger = INFO, R
# # configure log output type as file
# log4j.appender.R = org.apache.log4j.DailyRollingFileAppender
# #log filename
# log4j.appender.R.file = ./logRecord.log
# # append
# log4j.appender.R.Append = true
# log4j.appender.R.layout = org.apache.log4j.PatternLayout
# log4j.appender.R.layout.ConversionPattern = %n%d%p[%l]%m%n
#
# log4j.appender.R.DatePattern='.' yyyy-MM-dd log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

3)mybatis-config.xml

<?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>
<!-- 引用db.properties配置文件 -->
<properties resource="db.properties"/>
<typeAliases>
<package name="com.dx.test.model"/>
</typeAliases>
<!-- 对事务的管理和连接池的配置 -->
<environments default="mysql_jdbc">
<environment id="oracle_jdbc">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment> <environment id="mysql_jdbc">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${name}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--
<mappers>
<mapper resource="resources/mapper/TaskAutoExecutePlanMapper.xml"/>
</mappers>
-->
<mappers>
<mapper class="com.dx.test.dao.ParentDao"></mapper>
<mapper class="com.dx.test.dao.ChildDao"></mapper>
</mappers>
</configuration>

注意:

1)上边mybatis-config.xml中配置datasource可以配置多个,在<environments default="mysql_jdbc">中指定启用配置;

2)因我们这里使用的是mybatis Java API技术,因此mappers下的mapper不需要配置*Mapper.xml,直接指定Mapper类即可,上边配置的ParentDao和ChildDao都是Mapper接口。

在com.dx.test.model下创建model类Parent/Child:

Parent类:

package com.dx.test;

import java.util.List;

public class Parent {
private Long id;
private String name;
private List<Child> childList; ...... @Override
public String toString() {
return "Parent{" +
"id=" + id +
", name='" + name + '\'' +
", childList=" + childList +
'}';
}
}

Child类:

package com.dx.test;

public class Child {
private Long id;
private String name;
private Long parentId;
private Parent parent; ...... @Override
public String toString() {
return "Child{" +
"id=" + id +
", name='" + name + '\'' +
", parentId=" + parentId +
", parent=" + parent +
'}';
}
}

2)在mysql中新建mydb,并创建parent,child两张主子表;

创建和插叙数据语句如下:

CREATE DATABASE  IF NOT EXISTS `mydb` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `mydb`;
-- MySQL dump 10.13 Distrib 8.0.18, for macos10.14 (x86_64)
--
-- Host: localhost Database: mydb
-- ------------------------------------------------------
-- Server version 8.0.17 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; --
-- Dumping data for table `child`
-- LOCK TABLES `child` WRITE;
/*!40000 ALTER TABLE `child` DISABLE KEYS */;
INSERT INTO `child` VALUES (1,'child1',1),(2,'child2',1),(3,'child2-1',2),(4,'child2-2',2);
/*!40000 ALTER TABLE `child` ENABLE KEYS */;
UNLOCK TABLES; --
-- Dumping data for table `parent`
-- LOCK TABLES `parent` WRITE;
/*!40000 ALTER TABLE `parent` DISABLE KEYS */;
INSERT INTO `parent` VALUES (1,'test1'),(2,'test2');
/*!40000 ALTER TABLE `parent` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2019-11-12 21:09:47

3)一对多的用法;

定义Mapper类ParentDao:

package com.dx.test.dao;

import com.dx.test.Child;
import com.dx.test.Parent;
import org.apache.ibatis.annotations.*; import java.util.List; @Mapper
public interface ParentDao {
@Options(useCache = true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)
@Results(id = "parentResult", value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "name", column = "name"),
@Result(property = "childList", javaType = List.class, many = @Many(select = "selectChildsByParentId"), column = "id")
})
@Select("select * from parent where id = #{id}")
Parent queryParentById(Long id); @Options(useCache = true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)
@Results(id="childResult",value={
@Result(property = "id",column = "id",id=true),
@Result(property = "name",column = "name"),
@Result(property = "parentId",column = "parent_id")
})
@Select({"select t10.* from child t10 where t10.parent_id=#{parentId}"})
List<Child> selectChildsByParentId(@Param("parentId") Long parentId);
}

1)queryParentById(Long id):根据parent.id查询parent实体,并在@Reusults中定义了chilList的装配方法;

2)selectChildsByParentId(Long parentId):根据parentId,查询子类实体列表。

测试代码:

package com.dx.test;

import com.dx.test.dao.ChildDao;
import com.dx.test.dao.ParentDao;
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.IOException;
import java.io.InputStream; public class MybatisTest {
public static void main(String[] args) throws IOException {
final String resource = "mybatis-config.xml";
SqlSessionFactory factory = null; InputStream is = Resources.getResourceAsStream(resource);
factory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = factory.openSession();
ParentDao parentDao = sqlSession.getMapper(ParentDao.class);
Parent parent = parentDao.queryParentById(1L);
System.out.println(parent);
}
}

输出结果:

Parent{id=1, name='test1', childList=[Child{id=1, name='child1', parentId=1, parent=null}, Child{id=2, name='child2', parentId=1, parent=null}]}

4)多对一的用法。

定义mapper类ChildDao:

package com.dx.test.dao;

import com.dx.test.Child;
import com.dx.test.Parent;
import org.apache.ibatis.annotations.*; @Mapper
public interface ChildDao {
@Options(useCache = true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)
@Results(id = "childResult", value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "name", column = "name"),
@Result(property = "parentId", column = "parent_id"),
@Result(property = "parent", javaType = Parent.class, one = @One(select = "selectParentById"), column = "parent_id")
})
@Select({"select * from child where id=#{id}"})
Child selectById(@Param("id") Long id); @Options(useCache = true, flushCache = Options.FlushCachePolicy.FALSE, timeout = 60000)
@Results(id = "parentResult", value = {
@Result(property = "id", column = "id", id = true),
@Result(property = "name", column = "name")
})
@Select("select * from parent where id = #{id}")
Parent selectParentById(@Param("parentId") Long id); }

测试代码:

package com.dx.test;

import com.dx.test.dao.ChildDao;
import com.dx.test.dao.ParentDao;
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.IOException;
import java.io.InputStream; public class MybatisTest {
public static void main(String[] args) throws IOException {
final String resource = "mybatis-config.xml";
SqlSessionFactory factory = null; InputStream is = Resources.getResourceAsStream(resource);
factory = new SqlSessionFactoryBuilder().build(is); SqlSession sqlSession = factory.openSession(); ChildDao childDao = sqlSession.getMapper(ChildDao.class);
Child child = childDao.selectById(1L);
System.out.println(child);
}
}

输出结果:

Child{id=1, name='child1', parentId=1, parent=Parent{id=1, name='test1', childList=null}}

5)一对多在查询子表时传递多个参数

/**
* 按顾客id查询其购物车(商家->商品 一对多查询)
* @param consumerId 顾客id
* @return 购物车商品列表
*/
@Select("select distinct saler.id,saler.shopname,#{consumerId} as consumerId from shoppingcart \n" +
"join saler on saler.id = shoppingcart.salerId \n" +
"where consumerId = #{consumerId}")
@Results(
@Result(
property = "goods",
column = "{salerId = id,consumerId = consumerId}",
many = @Many(select = "cn.datacharm.springbootvuecli.dao.CartMapper.findGoodsBySalerId")
)
)
List<Shop> findCartById(Integer consumerId); @Select("select \n" +
"sid,consumerId,productName,price,photo,\n" +
"shoppingcart.salerId,\n" +
"shoppingcart.productId,\n" +
"shoppingcart.amount\n" +
"from shoppingcart\n" +
"join saler_inventory on shoppingcart.salerId = saler_inventory.salerId\n" +
"and shoppingcart.productId = saler_inventory.productId\n" +
"where shoppingcart.salerId = #{salerId}\n"+
"and consumerId = #{consumerId}" )
List<Goods> findGoodsBySalerId(Integer salerId,Integer consumerId);

@Result中column = "{salerId = id,consumerId = consumerId}"
表示把id列和consumerId列取出
id列值使用salerId,consumerId列使用consumerId 表示(类似别名,对应子查询参数)
然后以这两个参数进行子查询

参考:https://blog.csdn.net/weixin_43297055/article/details/93635950

MyBatis(六):Mybatis Java API编程实现一对多、一对一的更多相关文章

  1. 利用SparkLauncher 类以JAVA API 编程的方式提交Spark job

    一.环境说明和使用软件的版本说明: hadoop-version:hadoop-2.9.0.tar.gz spark-version:spark-2.2.0-bin-hadoop2.7.tgz jav ...

  2. HDFS shell操作及HDFS Java API编程

    HDFS shell操作及HDFS Java API编程 1.熟悉Hadoop文件结构. 2.进行HDFS shell操作. 3.掌握通过Hadoop Java API对HDFS操作. 4.了解Had ...

  3. 使用JAVA API编程实现简易Habse操作

    使用JAVA API编程实现下面内容: 1.创建<王者荣耀>游戏玩家信息表gamer,包含列族personalInfo(个人信息).recordInfo(战绩信息).assetsInfo( ...

  4. MyBatis(七):mybatis Java API编程实现增、删、改、查的用法

    最近工作中用到了mybatis的Java API方式进行开发,顺便也整理下该功能的用法,接下来会针对基本部分进行学习: 1)Java API处理一对多.多对一的用法: 2)增.删.改.查的用法: 3) ...

  5. 六、Java API操作zookeeper节点

    目录 前文 pom.xml文件增加依赖 新建java文件:ZookeeperTest GitHub文件下载 前文 一.CentOS7 hadoop3.3.1安装(单机分布式.伪分布式.分布式 二.JA ...

  6. 9. 使用ZooKeeper Java API编程

    ZooKeeper是用Java开发的,3.4.6版本的Java API文档可以在http://zookeeper.apache.org/doc/r3.4.6/api/index.html上找到. Ti ...

  7. RabbitMQ的Java API编程

    1.创建Maven工程,pom.xml引入依赖: <dependency> <groupId>com.rabbitmq</groupId> <artifact ...

  8. HBase环境搭建、shell操作及Java API编程

    一. 1.掌握Hbase在Hadoop集群体系结构中发挥的作用和使过程. 2.掌握安装和配置HBase基本方法. 3.掌握HBase shell的常用命令. 4.使用HBase shell命令进行表的 ...

  9. Hbase(六) hbase Java API

    一. 几个主要 Hbase API 类和数据模型之间的对应关系: 1. HBaseAdmin关系: org.apache.hadoop.hbase.client.HBaseAdmin作用:提供了一个接 ...

随机推荐

  1. 编写可维护的JavaScript-随笔(四)

    避免使用全局变量 一.全局变量带来的问题 a)      命名冲突 i.          当全局变量和全局函数越来越多时,发生命名冲突的概率也随之增高 ii.          如果函数中使用了外部 ...

  2. List加载因子和扩容因子

    List.Map.set的加载因子,默认初始容量和扩容增量 首先,这三个概念说下.初始大小,就是创建时可容纳的默认元素个数:加载因子,表示某个阀值,用0~1之间的小数来表示,当已有元素占比达到这个阀值 ...

  3. Tomcat内存溢出解决方法

    Java内存溢出详解 一.常见的Java内存溢出有以下三种: 1. java.lang.OutOfMemoryError: Java heap space ----JVM Heap(堆)溢出 JVM在 ...

  4. 利用tcpdump抓取网络包

    1.下载并安装tcpdump 下载地址:tcpdump 安装tcpdump,连接adb adb push tcpdump /data/local/tcpdump adb shell chmod 675 ...

  5. 多态典型用例之virtual

    多态典型用例之virtual 参考:https://www.cnblogs.com/dormant/p/5223215.html 1.虚函数(virtual) (1)在某基类中声明为 virtual ...

  6. [TJOI2018]最长上升子序列

    Link 动态维护LIS? 观察题目:在第 i 轮操作时,将数字 i 插入 插入的数字是当前最大的 如果答案与上次不同,新的LIS必以 i 结尾 以 i 结尾的LIS无法再伸长(因为比 i 小的都插入 ...

  7. JS实现俄罗斯方块

    在80后.90后的儿时记忆里,俄罗斯方块是必备的消遣小游戏,它的玩法非常简单基本大家都懂,但如何用编程语言开发一款儿时同款「俄罗斯方块」,恐怕知道的同学就很少啦. 位置掩码和旋转掩码 俄罗斯方块游戏中 ...

  8. 【转】Linux 网络工具详解之 ip tuntap 和 tunctl 创建 tap/tun 设备

    原文:https://www.cnblogs.com/bakari/p/10449664.html -------------------------------------------------- ...

  9. Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'org_mer_id' in where clause is ambiguous

    ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolatio ...

  10. 牛客NOIP暑期七天营-提高组6C:分班问题 (组合数)

    题意:A班有N个人,B班有M个人,现在要组成一个新的班级C班,为了公平,从AB班各抽相同人数的人. 现在求所有方案中,人数之和是多少. 思路:即求Σ k*C(N,k)*C(M,k);    先忽略这个 ...