MyBatis(六):Mybatis Java API编程实现一对多、一对一
最近工作中用到了mybatis的Java API方式进行开发,顺便也整理下该功能的用法,接下来会针对基本部分进行学习:
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编程实现一对多、一对一的更多相关文章
- 利用SparkLauncher 类以JAVA API 编程的方式提交Spark job
一.环境说明和使用软件的版本说明: hadoop-version:hadoop-2.9.0.tar.gz spark-version:spark-2.2.0-bin-hadoop2.7.tgz jav ...
- HDFS shell操作及HDFS Java API编程
HDFS shell操作及HDFS Java API编程 1.熟悉Hadoop文件结构. 2.进行HDFS shell操作. 3.掌握通过Hadoop Java API对HDFS操作. 4.了解Had ...
- 使用JAVA API编程实现简易Habse操作
使用JAVA API编程实现下面内容: 1.创建<王者荣耀>游戏玩家信息表gamer,包含列族personalInfo(个人信息).recordInfo(战绩信息).assetsInfo( ...
- MyBatis(七):mybatis Java API编程实现增、删、改、查的用法
最近工作中用到了mybatis的Java API方式进行开发,顺便也整理下该功能的用法,接下来会针对基本部分进行学习: 1)Java API处理一对多.多对一的用法: 2)增.删.改.查的用法: 3) ...
- 六、Java API操作zookeeper节点
目录 前文 pom.xml文件增加依赖 新建java文件:ZookeeperTest GitHub文件下载 前文 一.CentOS7 hadoop3.3.1安装(单机分布式.伪分布式.分布式 二.JA ...
- 9. 使用ZooKeeper Java API编程
ZooKeeper是用Java开发的,3.4.6版本的Java API文档可以在http://zookeeper.apache.org/doc/r3.4.6/api/index.html上找到. Ti ...
- RabbitMQ的Java API编程
1.创建Maven工程,pom.xml引入依赖: <dependency> <groupId>com.rabbitmq</groupId> <artifact ...
- HBase环境搭建、shell操作及Java API编程
一. 1.掌握Hbase在Hadoop集群体系结构中发挥的作用和使过程. 2.掌握安装和配置HBase基本方法. 3.掌握HBase shell的常用命令. 4.使用HBase shell命令进行表的 ...
- Hbase(六) hbase Java API
一. 几个主要 Hbase API 类和数据模型之间的对应关系: 1. HBaseAdmin关系: org.apache.hadoop.hbase.client.HBaseAdmin作用:提供了一个接 ...
随机推荐
- 剑指前端(前端入门笔记系列)——Math对象
Math对象 ECMAScript将一些常用的数学公式和信息封装到了一个对象中——Math对象,为我们实现数学方面的计算功能提供了便捷,而且该对象还提供了辅助完成这些计算的属性和方法 属性 con ...
- Spring容器的refresh()介绍
Spring容器的refresh()[创建刷新]; 1.prepareRefresh()刷新前的预处理; 1).initPropertySources()初始化一些属性设置;子类自定义个性化的属性设置 ...
- centos安装redis并且加入开机启动
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/weixin_41114593/articl ...
- vue 指令中el 的 parentNode 为空的问题
在项目中,突然发现在用vue指令的时候,发现元素el的父元素parentNode变成了null. 代码: if (el.parentNode && !Vue.prototype.$_h ...
- 设计模式之动态代理(JDK代理)
动态代理跟静态代理一个很重要的区别在于,动态代理是在内存是中的,是在代码编译期后在内存是实现的,而静态代理是我们自己编写代理类,编译后生成class文件.动态代理需要借助两个类:java.lang.r ...
- docker cannot stop container问题解决
docker 容器在启动时出现异常,删除容器或者暂停容器时会出现cannot stop container 先使用sudo aa-remove-unknown ,再进行其他操作 lgj@lgj-Len ...
- 【Spring Boot】Spring Boot之五种容器启动后进行相关应用初始化操作方法
一.方式一,使用ApplicationListener<E extends ApplicationEvent>监听ContextRefreshedEvent事件 /** * @author ...
- Junit测试入门
junit测试的6大注解 @BeforeClass 最先执行,在整个测试类中只会执行一次,所以它只能声明一次,并且被它标注的方法必须声明为static @Before 可以声明多个方 ...
- 快速的在linux服务器上安装jdk8
1.执行命令 yum -y list java* 查看可安装java版本.执行成功后可以看见如下的结果 选择一个java版本进行安装,这里我们希望安装java1.8,因为我们的机器是64位的,所以选择 ...
- 【Yellow Cards CodeForces - 1215A 】【贪心】
该题难点在于求最小的离开数,最大的没什么好说的,关键是求最小的. 可以这样去想,最小的离开数就是每个人获得的牌数等于他所能接受的最大牌数-1,这样就可以直接比较m=a1(k1-1)+a2(k2-1)与 ...