Mybatis当中的多对多映射关系(非注解版)

简介: 学习mybatis时,不用和spring集成, 不用注解,可以了解得多一些, 在这之上,使用注解和spring集成, 乃至到spring boot, 其间的传递路径才不会迷路。

学习mybatis时,不用和spring集成,

不用注解,可以了解得多一些,

在这之上,使用注解和spring集成,

乃至到spring boot,

其间的传递路径才不会迷路。


照旧,上差不多全部代码,

又不是写书,不怕篇幅长,

方便自己日后回忆。


数据库语句:


CREATE TABLE tb_user (
  id INT(11) PRIMARY KEY AUTO_INCREMENT,
  USERNAME VARCHAR(18),
  LOGINNAME VARCHAR(18),
  PASSWORD VARCHAR(18),
  PHONE VARCHAR(18),
  ADDRESS VARCHAR(18)
);

INSERT INTO tb_user(username, loginname, password, phone, address)
VALUES ('jack', 'jack', '123456', '16534231234', 'guangzhou');

INSERT INTO tb_user(username, loginname, password, phone, address)
VALUES ('sky', 'chen', '12345678', '16512231234', 'shanghai');

INSERT INTO tb_user(username, loginname, password, phone, address)
VALUES ('tom', 'gang', '123678', '13512231234', 'beijing');


CREATE TABLE tb_article(
  id INT PRIMARY KEY AUTO_INCREMENT,
  NAME VARCHAR(18),
  PRICE DOUBLE,
  REMARK VARCHAR(18)
);

INSERT INTO tb_article(NAME,PRICE,REMARK)
VALUES('Java', 108.9, 'ligang');
INSERT INTO tb_article(NAME,PRICE,REMARK)
VALUES('Android', 99.9, 'ligang');
INSERT INTO tb_article(NAME,PRICE,REMARK)
VALUES('ios', 89.4, 'ligang');
INSERT INTO tb_article(NAME,PRICE,REMARK)
VALUES('SpringMVC', 108.9, 'xiaowenjie');
INSERT INTO tb_article(NAME,PRICE,REMARK)
VALUES('Python', 68, 'chengang');

CREATE TABLE tb_order(
  id INT PRIMARY KEY AUTO_INCREMENT,
  CODE VARCHAR(32),
  TOTAL DOUBLE,
  USER_ID INT,
  FOREIGN KEY (USER_ID) REFERENCES tb_user(ID)
);

INSERT INTO tb_order(CODE, TOTAL, USER_ID)
VALUES('62345ASDADFA34SASDF', 388.6, 1);
INSERT INTO tb_order(CODE, TOTAL, USER_ID)
VALUES('2342SD234SASDF', 321.6, 1);
INSERT INTO tb_order(CODE, TOTAL, USER_ID)
VALUES('2W4WEADF4SASDF', 588.6, 2);
INSERT INTO tb_order(CODE, TOTAL, USER_ID)
VALUES('ZADWR234SASDF', 31.6, 2);


CREATE TABLE tb_item(
  ORDER_ID INT,
  ARTICLE_ID INT,
  AMOUNT INT,
  PRIMARY KEY(ORDER_ID, ARTICLE_ID),
  FOREIGN KEY (ORDER_ID) REFERENCES tb_order(ID),
  FOREIGN KEY (ARTICLE_ID) REFERENCES tb_article(ID)
);

INSERT INTO tb_item(order_id, article_id, amount)
VALUES(1, 1, 1);
INSERT INTO tb_item(order_id, article_id, amount)
VALUES(1, 2, 1);
INSERT INTO tb_item(order_id, article_id, amount)
VALUES(1, 3, 2);
INSERT INTO tb_item(order_id, article_id, amount)
VALUES(2, 4, 2);
INSERT INTO tb_item(order_id, article_id, amount)
VALUES(2, 1, 1);
INSERT INTO tb_item(order_id, article_id, amount)
VALUES(3, 3, 2);
INSERT INTO tb_item(order_id, article_id, amount)
VALUES(4, 4, 2);
INSERT INTO tb_item(order_id, article_id, amount)
VALUES(4, 1, 1);

user.java


package org.fkit.domain;

import java.util.List;

public class User {
	private Integer id;
	private String username;
	private String loginname;
	private String password;
	private String phone;
	private String address;
	private List<Order> orders;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public List<Order> getOrders() {
		return orders;
	}
	public void setOrders(List<Order> orders) {
		this.orders = orders;
	}
	
	
	
	

}

article.java


package org.fkit.domain;

import java.util.List;

public class Article {
	private Integer id;
	private String name;
	private String price;
	private String remark;
	private List<Order> orders;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPrice() {
		return price;
	}
	public void setPrice(String price) {
		this.price = price;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	public List<Order> getOrders() {
		return orders;
	}
	public void setOrders(List<Order> orders) {
		this.orders = orders;
	}
	
	
	

}

Article.java
package org.fkit.domain;

import java.util.List;

public class Order {
	private Integer id;
	private String code;
	private Double total;
	private User user;
	private List<Article> articles;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public Double getTotal() {
		return total;
	}
	public void setTotal(Double total) {
		this.total = total;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public List<Article> getArticles() {
		return articles;
	}
	public void setArticles(List<Article> articles) {
		this.articles = articles;
	}
	
	
	

}

usermapper.xml


<?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="org.fkit.mapper.UserMapper">
	<resultMap type="org.fkit.domain.User" id="userResultMap">
		<id property="id" column="id" />
		<result property="username" column="username"/>
		<result property="loginname" column="loginname"/>
		<result property="password" column="password"/>
		<result property="phone" column="phone"/>
		<result property="address" column="address"/>
		<collection property="orders" javaType="ArrayList"
		column="id" ofType="org.fkit.domain.User"
		select="org.fkit.mapper.OrderMapper.selectOrderByUserId"
		fetchType="lazy">
			<id property="id" column="id" />
			<result property="code" column="code" />
			<result property="total" column="total" />
		</collection>
	</resultMap>
	
	<select id="selectUserById" parameterType="int" resultMap="userResultMap">
		SELECT * FROM tb_user WHERE id = #{id}
	</select>
</mapper>

articlemapper.xml


<?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="org.fkit.mapper.ArticleMapper">
	<select id="selectArticleByOrderId" parameterType="int" resultType="org.fkit.domain.Article">
		SELECT * FROM tb_article WHERE id IN (
			SELECT article_id FROM tb_item WHERE order_id=#{id}
		)
	</select>
	
</mapper>

ordermapper.xml


<?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="org.fkit.mapper.OrderMapper">
	<resultMap type="org.fkit.domain.Order" id="orderResultMap">
		<id property="id" column="oid" />
		<result property="code" column="code" />
		<result property="total" column="total" />
		<association property="user" javaType="org.fkit.domain.User">
			<id property="id" column="id" />
			<result property="username" column="username"/>
			<result property="loginname" column="loginname"/>
			<result property="password" column="password"/>
			<result property="phone" column="phone"/>
			<result property="address" column="address"/>
		</association>
		
		<collection property="articles" javaType="ArrayList"
		column="oid" ofType="org.fkit.domain.Article"
		select="org.fkit.mapper.ArticleMapper.selectArticleByOrderId"
		fetchType="lazy">
			<id property="id" column="id" />
			<result property="name" column="name"/>
			<result property="price" column="price"/>
			<result property="remark" column="remark"/>
		
		</collection>
		
	</resultMap>
	<select id="selectOrderById" parameterType="int" resultMap="orderResultMap">
		SELECT u.*, o.id AS oid, CODE, TOTAL, USER_ID
		FROM tb_user u, tb_order o
		WHERE u.id = o.USER_ID
		AND o.id=#{id}
	</select>
	<select id="selectOrderByUserId" parameterType="int" resultType="org.fkit.domain.Order">
		SELECT * FROM tb_order WHERE user_id = #{id}
	</select>
	
</mapper>

ManyToManyTest.java


package org.fkit.tst;


import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.fkit.domain.Article;

import org.fkit.domain.Order;

import org.fkit.domain.User;
import org.fkit.factory.FKSqlSessionFactory;

import org.fkit.mapper.OrderMapper;

import org.fkit.mapper.UserMapper;


public class ManyToManyTest {

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		SqlSession session = FKSqlSessionFactory.getSqlSession();
		
		ManyToManyTest t = new ManyToManyTest();
		t.testSelectUserById(session);
		t.testSelectOrderById(session);

		session.commit();
		session.close();

	}
	
	public void testSelectUserById(SqlSession session) {
		UserMapper um = session.getMapper(UserMapper.class);
		User user = um.selectUserById(1);
		System.out.println(user.getId() + " === " + user.getUsername());
		List<Order> orders = user.getOrders();
		for (Order order : orders) {
			System.out.println(order.getCode());
		}
	}
	
	public void testSelectOrderById(SqlSession session) {
		OrderMapper om = session.getMapper(OrderMapper.class);
		Order order = om.selectOrderById(2);
		System.out.println(order.getId() + " @@@ " + order.getCode() + " @@@ " + order.getTotal());
		User user = order.getUser();
		System.out.println(user.getUsername());
		List<Article> articles = order.getArticles();
		for(Article article : articles) {
			System.out.println(article.getName());
		}
	}

}

518e9ce45ad0e810f675fcf48eb484a58d064584
目录
相关文章
|
8天前
|
SQL Java 数据库连接
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
MyBatis-Plus是一个MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。本文讲解了最新版MP的使用教程,包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段等核心功能。
【MyBatisPlus·最新教程】包含多个改造案例,常用注解、条件构造器、代码生成、静态工具、类型处理器、分页插件、自动填充字段
|
17天前
|
SQL 缓存 Java
【详细实用のMyBatis教程】获取参数值和结果的各种情况、自定义映射、动态SQL、多级缓存、逆向工程、分页插件
本文详细介绍了MyBatis的各种常见用法MyBatis多级缓存、逆向工程、分页插件 包括获取参数值和结果的各种情况、自定义映射resultMap、动态SQL
【详细实用のMyBatis教程】获取参数值和结果的各种情况、自定义映射、动态SQL、多级缓存、逆向工程、分页插件
|
18天前
|
SQL 缓存 Java
MyBatis如何关闭一级缓存(分注解和xml两种方式)
MyBatis如何关闭一级缓存(分注解和xml两种方式)
52 5
|
18天前
|
Java 数据库连接 mybatis
Mybatis使用注解方式实现批量更新、批量新增
Mybatis使用注解方式实现批量更新、批量新增
39 3
|
25天前
|
SQL 存储 数据库
深入理解@TableField注解的使用-MybatisPlus教程
`@TableField`注解在MyBatis-Plus中是一个非常灵活和强大的工具,能够帮助开发者精细控制实体类与数据库表字段之间的映射关系。通过合理使用 `@TableField`注解,可以实现字段名称映射、自动填充、条件查询以及自定义类型处理等高级功能。这些功能在实际开发中,可以显著提高代码的可读性和维护性。如果需要进一步优化和管理你的MyBatis-Plus应用程
105 3
|
23天前
|
Java 数据库连接 mybatis
Mybatis使用注解方式实现批量更新、批量新增
Mybatis使用注解方式实现批量更新、批量新增
41 1
|
2月前
|
SQL XML Java
mybatis复习04高级查询 一对多,多对一的映射处理,collection和association标签的使用
文章介绍了MyBatis中高级查询的一对多和多对一映射处理,包括创建数据库表、抽象对应的实体类、使用resultMap中的association和collection标签进行映射处理,以及如何实现级联查询和分步查询。此外,还补充了延迟加载的设置和用法。
mybatis复习04高级查询 一对多,多对一的映射处理,collection和association标签的使用
|
2月前
|
SQL XML Java
mybatis复习02,简单的增删改查,@Param注解多个参数,resultType与resultMap的区别,#{}预编译参数
文章介绍了MyBatis的简单增删改查操作,包括创建数据表、实体类、配置文件、Mapper接口及其XML文件,并解释了`#{}`预编译参数和`@Param`注解的使用。同时,还涵盖了resultType与resultMap的区别,并提供了完整的代码实例和测试用例。
mybatis复习02,简单的增删改查,@Param注解多个参数,resultType与resultMap的区别,#{}预编译参数
|
2月前
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
3月前
|
SQL Java 数据库
5、Mybatis-Plus 常用注解
这篇文章详细介绍了Mybatis-Plus中常用的注解,包括解决实体类与数据库表名不一致、字段不匹配的问题,主键生成策略的配置,以及逻辑删除的实现方法。
5、Mybatis-Plus 常用注解