Java进阶知识36 mybatis+Oracle 单向多对多关联 之CRUD操作【xml 版】

本文知识点(目录):

      1、导读
          1.1、技术概述
          1.2、本文使用的jar包、项目结构图
      2、本文所有代码(xml版)
          2.1、数据库脚本(oracle.sql)
          2.2、mybatis.xml 核心配置文件
          2.3、MyBatisUtils 工具类(用于连接数据库)
          2.4、实体类(Order、Product、OrderProductLink)以及对应的xxxxxMapper.xml 配置文件
          2.5、DAO层(Order类对应的接口及接口实现类、Product类对应的接口及接口实现类 )
          2.6、测试类 (TestOrderDao)及测试结果



1、导读              

1.1、技术概述

    a.本文使用的是Oracle+mybatis框架,单向多对多关联,以Order为主(数据表之间的关系:orders和product是从表,product_orders是主表(中间表))

    b.实现了CURD等操作:新增、修改、删除、删除指定订单下的所有商品、批量删除、查询全部订单、根据id查询商品、根据id查询指定订单下的所有商品

    c.本文只测试/演示DAO层与数据库之间的连接以及数据的CRUD操作

    d.本项目的使用环境:MyEclipse10.7 + JDK1.8 + Oracle11g + mybatis3.1.1

1.2、本文使用的jar包、项目结构图

     

2、本文所有代码(xml版)  

2.1、数据库脚本(oracle.sql)

 1 -- 多对多
 2 -- 1、创建表
 3 create table product(
 4     id number(6) primary key,
 5     name varchar2(20),
 6     price number(6,2)
 7 );
 8 
 9 create table orders(
10     id number(6) primary key,
11     num varchar2(20),
12     address varchar2(20)
13 );
14 
15 create table product_orders(
16     product_id number(6),
17     orders_id number(6),
18     primary key(product_id,orders_id)
19     constraint product_orders_fk foreign key(product_id) references product(id)
20     constraint orders_product_fk foreign key(orders_id) references orders(id)
21 );
22 
23 -- 2、创建序列
24 create sequence product_seq
25 minvalue 1    --最小值
26 maxvalue 99999    -- 最大值
27 increment by 1    --从1开始计数
28 start with 1    --每次加1
29 nocycle        --一直累加,不循环
30 nocache;    --不建缓冲区。
31 
32 create sequence orders_seq
33 minvalue 1    
34 maxvalue 99999    
35 increment by 1 
36 start with 1    
37 nocycle        
38 nocache;    
39 
40 -- 3、创建触发器
41 create or replace trigger product_tg
42   before insert on product for each row 
43     begin
44       select product_seq.Nextval into:new.id from dual;
45   end;
46 
47 create or replace trigger orders_tg
48   before insert on orders for each row 
49     begin
50       select orders_seq.Nextval into:new.id from dual;
51   end;
52 
53   

2.2、mybatis.xml 核心配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 4 <configuration>
 5     <typeAliases>  
 6         <typeAlias type="com.shore.m2m.entity.Order" alias="Order" />  
 7         <typeAlias type="com.shore.m2m.entity.Product" alias="Product" />  
 8         <typeAlias type="com.shore.m2m.entity.OrderProductLink" alias="OrderProductLink" />  
 9     </typeAliases>  
10     
11     <environments default="development">
12         <environment id="development">
13             <transactionManager type="JDBC" />
14             <dataSource type="POOLED">
15                 <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
16                 <property name="url" value="jdbc:oracle:thin:@localhost:1521:shoreid" />
17                 <property name="username" value="zhangsan" />
18                 <property name="password" value="123456" />
19             </dataSource>
20         </environment>
21     </environments>
22 
23     <mappers><!-- 5、通过SqlSession对象读取XXXXXMapper.xml映射文件中的对应操作id,从而获取sql语句; -->
24         <mapper resource="com/shore/m2m/entity/ProductMapper.xml"/>
25         <mapper resource="com/shore/m2m/entity/OrderMapper.xml"/>
26     </mappers>
27 </configuration>

2.3、MyBatisUtils 工具类(用于连接数据库)

 1 package com.shore.common.utils;
 2 
 3 import java.io.Reader;
 4 
 5 import org.apache.ibatis.io.Resources;
 6 import org.apache.ibatis.session.SqlSession;
 7 import org.apache.ibatis.session.SqlSessionFactory;
 8 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 9 
10 /**
11  * @author DSHORE/2020-3-12
12  *
13  */
14 public class MyBatisUtils {
15     private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
16     private static SqlSessionFactory sqlSessionFactory;
17     
18     static{
19         try {
20             //1、读取配置
21             Reader reader = Resources.getResourceAsReader("mybatis.xml");
22             //2、创建SqlSessionFactory
23             sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
24         } catch (Exception e) {
25             e.fillInStackTrace();
26             throw new RuntimeException(e);
27         }
28     }
29     
30     private MyBatisUtils() { }
31     
32     //3、获取SqlSession
33     public static SqlSession getSqlSession(){
34         SqlSession sqlSession = threadLocal.get();
35         if (sqlSession == null) {//如果上面获取不到SQLSession,将通过下面的方式来获取
36             sqlSession = sqlSessionFactory.openSession();
37         }
38         return sqlSession;
39     }
40     
41     //7、关闭SqlSession
42     public static void closeSqlSession() {
43         SqlSession sqlSession = threadLocal.get();
44         if (sqlSession != null) {
45             sqlSession.close();
46             threadLocal.remove();
47         }
48     }
49 }

2.4、实体类(Order、Product、OrderProductLink)以及对应的xxxxxMapper.xml 配置文件

OrderProductLink.java

 1 package com.shore.m2m.entity;
 2 
 3 /**
 4  * @author DSHORE/2020-3-18
 5  * OrderProductLink维护Order和Product之间的关联关系
 6  */
 7 public class OrderProductLink {
 8     private Order order;
 9     private Product product;
10 
11     //省略了Setter和Getter方法
12 }

Order.java

 1 package com.shore.m2m.entity;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * @author DSHORE/2020-3-17
 7  * mybatis:单向多对多关联,以Order为主
 8  */
 9 public class Order {
10     private Integer id;
11     private String num;
12     private String address;
13     private List<Product> products;//一个订单,可以有多件商品
14 
15     //省略了Setter和Getter方法
16 }

Product.java

 1 package com.shore.m2m.entity;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * @author DSHORE/2020-3-17
 7  * mybatis:单向多对多关联,以Order为主
 8  */
 9 public class Product {
10     private Integer id;
11     private String name;
12     private Float price;
13     private List<Order> orders; ////一件商品,可以有多个订单
14 
15     //省略了Setter和Getter方法
16 }

OrderMapper.xml 配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 <mapper namespace="orderNameSpace">
 6     <resultMap id="orderResultMap" type="com.shore.m2m.entity.Order">
 7         <id property="id" column="id"/>
 8         <result property="num" column="num"/>
 9         <result property="address" column="address"/>
10         <!--一对多关系配置:一件商品,可以有多个订单-->
11         <collection property="products" column="id" resultMap="productNameSpace.productResultMap"></collection>
12     </resultMap>
13     
14     <!--======================= 新增 ============================= -->
15     <insert id="addOrder" parameterType="com.shore.m2m.entity.Order">
16         <!-- 返回当前,刚刚插入的数据的id -->
17         <selectKey order="AFTER" keyProperty="id" resultType="int">
18             select max(id) as id from orders
19         </selectKey>
20         insert into
21             orders(num,address)
22         values(#{num,jdbcType=VARCHAR},#{address,jdbcType=VARCHAR})
23     </insert>
24     
25     <!--保存中间表的操作  product_orders -->
26     <insert id="saveOrderProduct" parameterType="com.shore.m2m.entity.OrderProductLink">
27         insert into 
28             product_orders(product_id,orders_id)
29         values(#{product.id,jdbcType=NUMERIC},#{order.id,jdbcType=NUMERIC})
30     </insert>
31 
32     
33     <!--======================= 修改 ============================= -->
34     <!-- 根据id修改orders表中的内容 -->
35     <update id="updateOrder" parameterType="com.shore.m2m.entity.Order">
36         update orders 
37         set 
38             <if test="num != null">
39                 num=#{num,jdbcType=VARCHAR},
40             </if>
41             <if test="address != null">
42                 address=#{address,jdbcType=NUMERIC}
43             </if>
44         where id=#{id,jdbcType=NUMERIC}
45     </update>
46     
47     <!-- 根据id,重新修改orders表和product表之间的关联关系 -->
48     <update id="updateOrderProduct" parameterType="com.shore.m2m.entity.OrderProductLink">
49         update product_orders 
50         set 
51             <if test=" product != null">
52                 orders_id=#{order.id,jdbcType=NUMERIC}
53             </if>
54         where product_id=#{product.id,jdbcType=NUMERIC}
55     </update>
56     
57     <!--===================== 根据id查询 =========================== -->
58     <select id="findById" parameterType="int" resultMap="orderResultMap">
59         select p.* 
60         from product p,orders o,product_orders po
61         where o.id = po.orders_id and p.id = po.product_id and o.id = #{id}
62     </select>
63     
64     <select id="findOrderByProductId" parameterType="int" resultMap="orderResultMap">
65         select o.* 
66         from product p,orders o,product_orders po
67         where o.id = po.orders_id and p.id = po.product_id and p.id = #{id}
68     </select>
69     
70     
71     <!--======================== 查询所有 ========================== -->
72     <select id="selectAll" resultMap="orderResultMap">
73         select * from orders
74     </select>
75     
76     <!--======================== 删除 ============================== -->
77     <!-- 删除订单 -->
78     <delete id="deleteByOrderId" parameterType="int">
79         delete from orders where id=#{id}
80     </delete>
81     
82     <!-- 根据orders_id解除中间表product_orders的关联关系 -->
83     <delete id="deleteOrderProductId" parameterType="int">
84         delete from product_orders where orders_id=#{id}
85     </delete>
86     
87     <!-- 根据product_id解除中间表product_orders的关联关系 -->
88     <delete id="deleteOrderProductId2" parameterType="int">
89         delete from product_orders where product_id=#{id}
90     </delete>
91 </mapper>

ProductMapper.xml 配置文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 <mapper namespace="productNameSpace">
 6     <resultMap id="productResultMap" type="com.shore.m2m.entity.Product">
 7         <id property="id" column="id"/>
 8         <result property="name" column="name"/>
 9         <result property="price" column="price"/>
10         <!--一对多关系配置:一个订单,可以有多件商品-->
11         <collection property="orders" column="id" resultMap="orderNameSpace.orderResultMap"></collection>
12     </resultMap>
13 
14     <!--======================= 新增 ============================= -->
15     <insert id="addProduct" parameterType="com.shore.m2m.entity.Product">
16         <!-- 返回当前,刚刚插入的数据的id -->
17         <selectKey order="AFTER" keyProperty="id" resultType="int">
18             select max(id) as id from product
19         </selectKey>
20         insert into
21             product(name,price)
22         values(#{name,jdbcType=VARCHAR},#{price,jdbcType=NUMERIC})
23         <!-- 批量新增 -->
24         <!-- insert into product(name,price)
25             <foreach collection="list" item="products" index="index" separator="union all">
26                 select
27                       #{products.name,jdbcType=VARCHAR},
28                       #{products.price,jdbcType=NUMERIC}
29                   from dual
30             </foreach> -->
31     </insert>
32 
33     <!--===================== 根据id查询 ========================== -->
34     <select id="findById" parameterType="int" resultMap="productResultMap">
35         select * from product where id = #{id,jdbcType=NUMERIC}
36     </select>
37     
38     <!--======================== 删除 ============================== -->
39     <delete id="deleteByProductId" parameterType="int">
40         delete from product where id=#{id}
41     </delete>
42     
43     <!-- ======================= 批量删除 ============================ -->
44     <delete id="batchDeleteById">
45         delete from product where id in 
46         <foreach item="ids" collection="list" open="(" separator="," close=")">
47             #{ids}
48         </foreach>
49     </delete>
50 </mapper>

2.5、DAO层(Order类对应的接口及接口实现类、Product类对应的接口及接口实现类 )

IOrderDao.java(接口类)

 1 package com.shore.m2m.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.shore.m2m.entity.Order;
 6 import com.shore.m2m.entity.OrderProductLink;
 7 
 8 /**
 9  * @author DSHORE/2020-3-18
10  *
11  */
12 public interface IOrderDao {
13     public int addOrder(Order order);//新增
14     
15     public int saveOrderProduct(OrderProductLink orderProductLink);//保存中间表product_orders
16     
17     public int updateOrder(Order order);//修改
18     
19     public int updateOrderProduct(OrderProductLink orderProductLink);//修改中间表的关联关系
20     
21     public Order findOrderByProductId(int id);//根据商品id查询订单
22     
23     public List<Order> findByOrderId(int id);//根据id查询:查询指定订单里面,有什么商品
24     
25     public List<Order> listAll();//查询所有(订单)
26     
27     public int deleteOrder(int id);//删除订单
28 
29     public int deleteOrderProduct(int id);//根据orders_id解除中间表product_orders的关联关系
30     
31     public int deleteOrderProduct2(int id);//根据product_id解除中间表product_orders的关联关系
32 }

OrderDao.java (接口类IOrderDao的实现类)

  1 package com.shore.m2m.dao.impl;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 
  6 import org.apache.ibatis.session.SqlSession;
  7 
  8 import com.shore.common.utils.MyBatisUtils;
  9 import com.shore.m2m.dao.IOrderDao;
 10 import com.shore.m2m.entity.Order;
 11 import com.shore.m2m.entity.OrderProductLink;
 12 
 13 /**
 14  * @author DSHORE/2020-3-18
 15  *
 16  */
 17 public class OrderDao implements IOrderDao {
 18     SqlSession sqlSession = null;
 19 
 20     @Override //新增
 21     public int addOrder(Order order) {
 22         sqlSession = MyBatisUtils.getSqlSession();
 23         try {
 24             return sqlSession.insert("orderNameSpace.addOrder", order);
 25         } catch (Exception e) {
 26             sqlSession.rollback();//如果出现异常,则,事务回滚
 27             System.out.println(e.getMessage());//打印异常信息
 28         } finally {
 29             sqlSession.commit();//提交事务
 30             MyBatisUtils.closeSqlSession();//关闭SqlSession
 31         }
 32         return 0;
 33     }
 34 
 35     @Override //保存中间表product_orders
 36     public int saveOrderProduct(OrderProductLink orderProductLink) {
 37         sqlSession = MyBatisUtils.getSqlSession();
 38         try {
 39             return sqlSession.insert("orderNameSpace.saveOrderProduct", orderProductLink);
 40         } catch (Exception e) {
 41             sqlSession.rollback();//如果出现异常,则,事务回滚
 42             System.out.println(e.getMessage());//打印异常信息
 43         } finally {
 44             sqlSession.commit();//提交事务
 45             MyBatisUtils.closeSqlSession();//关闭SqlSession
 46         }
 47         return 0;
 48     }
 49 
 50     @Override //修改
 51     public int updateOrder(Order order) {
 52         sqlSession = MyBatisUtils.getSqlSession();
 53         try {
 54             return sqlSession.insert("orderNameSpace.updateOrder", order);
 55         } catch (Exception e) {
 56             sqlSession.rollback();
 57             System.out.println(e.getMessage());
 58         } finally {
 59             sqlSession.commit();
 60             MyBatisUtils.closeSqlSession();
 61         }
 62         return 0;
 63     }
 64 
 65     @Override //修改中间表的关联关系
 66     public int updateOrderProduct(OrderProductLink orderProductLink) {
 67         sqlSession = MyBatisUtils.getSqlSession();
 68         try {
 69             return sqlSession.insert("orderNameSpace.updateOrderProduct", orderProductLink);
 70         } catch (Exception e) {
 71             sqlSession.rollback();
 72             System.out.println(e.getMessage());
 73         } finally {
 74             sqlSession.commit();
 75             MyBatisUtils.closeSqlSession();
 76         }
 77         return 0;
 78     }
 79 
 80     @Override //根据商品id查询订单
 81     public Order findOrderByProductId(int id) {
 82         List<Order> orders = new ArrayList<Order>();
 83         Order order = null;
 84         SqlSession sqlSession = MyBatisUtils.getSqlSession();
 85         try {
 86             orders = sqlSession.selectList("orderNameSpace.findOrderByProductId",id);
 87             if (orders != null && orders.size() > 0) {
 88                 order = orders.get(0);
 89             }
 90         } catch (Exception e) {
 91             System.out.println(e.getMessage());//打印错误/异常信息
 92         } finally {
 93             MyBatisUtils.closeSqlSession();//关闭SqlSession
 94         }    
 95         return order;
 96     }
 97     
 98     @Override //根据id查询:查询指定订单里面,有什么商品
 99     public List<Order> findByOrderId(int id) {
100         List<Order> orders = new ArrayList<Order>();
101         sqlSession = MyBatisUtils.getSqlSession();
102         try {
103             orders = sqlSession.selectList("orderNameSpace.findById",id);
104         } catch (Exception e) {
105             System.out.println(e.getMessage());//打印错误/异常信息
106         } finally {
107             MyBatisUtils.closeSqlSession();//关闭SqlSession
108         }    
109         return orders;
110     }
111 
112     @Override //查询所有(订单)
113     public List<Order> listAll() {
114         List<Order> orders = new ArrayList<Order>();
115         sqlSession = MyBatisUtils.getSqlSession();
116         try {
117             orders = sqlSession.selectList("orderNameSpace.selectAll");
118         } catch (Exception e) {
119             System.out.println(e.getMessage());
120         } finally {
121             MyBatisUtils.closeSqlSession();
122         }    
123         return orders;
124     }
125 
126     @Override //删除订单
127     public int deleteOrder(int id) {
128         sqlSession = MyBatisUtils.getSqlSession();
129         try {
130             return sqlSession.delete("orderNameSpace.deleteByOrderId", id);
131         } catch (Exception e) {
132             sqlSession.rollback();
133             System.out.println(e.getMessage());
134         } finally {
135             sqlSession.commit();
136             MyBatisUtils.closeSqlSession();
137         }
138         return 0;
139     }
140 
141     @Override //根据orders_id解除中间表product_orders的关联关系
142     public int deleteOrderProduct(int id) {
143         sqlSession = MyBatisUtils.getSqlSession();
144         try {
145             return sqlSession.delete("orderNameSpace.deleteOrderProductId", id);
146         } catch (Exception e) {
147             sqlSession.rollback();
148             System.out.println(e.getMessage());
149         } finally {
150             sqlSession.commit();
151             MyBatisUtils.closeSqlSession();
152         }
153         return 0;
154     }
155     
156     @Override //根据product_id解除中间表product_orders的关联关系
157     public int deleteOrderProduct2(int id) {
158         sqlSession = MyBatisUtils.getSqlSession();
159         try {
160             return sqlSession.delete("orderNameSpace.deleteOrderProductId2", id);
161         } catch (Exception e) {
162             sqlSession.rollback();
163             System.out.println(e.getMessage());
164         } finally {
165             sqlSession.commit();
166             MyBatisUtils.closeSqlSession();
167         }
168         return 0;
169     }
170 }

IProductDao.java(接口类)

 1 package com.shore.m2m.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.shore.m2m.entity.Product;
 6 
 7 /**
 8  * @author DSHORE/2020-3-18
 9  *
10  */
11 public interface IProductDao {
12     public int addProduct(Product product);//新增
13     
14     public Product findByProductId(int id);//根据id查询
15     
16     public int deleteProduct(int id);//删除
17     
18     public int batchDeleteById(List<Integer> ids);//批量删除
19 }

ProductDao.java(接口类IProductDao的实现类)

 1 package com.shore.m2m.dao.impl;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.apache.ibatis.session.SqlSession;
 7 
 8 import com.shore.common.utils.MyBatisUtils;
 9 import com.shore.m2m.dao.IProductDao;
10 import com.shore.m2m.entity.Product;
11 
12 /**
13  * @author DSHORE/2020-3-18
14  *
15  */
16 public class ProductDao implements IProductDao {
17 
18     @Override //新增
19     public int addProduct(Product product) {
20         SqlSession sqlSession = MyBatisUtils.getSqlSession();
21         try {
22             return sqlSession.insert("productNameSpace.addProduct", product);
23         } catch (Exception e) {
24             sqlSession.rollback();//如果出现异常,则,事务回滚
25             System.out.println(e.getMessage());//打印异常信息
26         } finally {
27             sqlSession.commit();//提交事务
28             MyBatisUtils.closeSqlSession();//关闭SqlSession
29         }
30         return 0;
31     }
32 
33     @Override //根据id查询
34     public Product findByProductId(int id) {
35         List<Product> products = new ArrayList<Product>();
36         Product product = null;
37         SqlSession sqlSession = MyBatisUtils.getSqlSession();
38         try {
39             products = sqlSession.selectList("productNameSpace.findById",id);
40             if (products != null && products.size() > 0) {
41                 product = products.get(0);
42             }
43         } catch (Exception e) {
44             System.out.println(e.getMessage());
45         } finally {
46             MyBatisUtils.closeSqlSession();
47         }    
48         return product;
49     }
50 
51     @Override //删除
52     public int deleteProduct(int id) {
53         SqlSession sqlSession = MyBatisUtils.getSqlSession();
54         try {
55             return sqlSession.delete("productNameSpace.deleteByProductId", id);
56         } catch (Exception e) {
57             sqlSession.rollback();
58             System.out.println("error:"+e.getMessage());
59         } finally {
60             sqlSession.commit();
61             MyBatisUtils.closeSqlSession();
62         }
63         return 0;
64     }
65 
66     @Override //批量删除
67     public int batchDeleteById(List<Integer> ids) {
68         SqlSession sqlSession = MyBatisUtils.getSqlSession();
69         try {
70             return sqlSession.delete("productNameSpace.batchDeleteById", ids);
71         } catch (Exception e) {
72             sqlSession.rollback();
73             System.out.println("error:"+e.getMessage());
74         } finally {
75             sqlSession.commit();
76             MyBatisUtils.closeSqlSession();
77         }
78         return 0;
79     }
80 }

2.6、测试类 (TestOrderDao)及测试结果

  1 package test.order;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 import org.junit.Test;
  6 
  7 import com.shore.m2m.dao.IOrderDao;
  8 import com.shore.m2m.dao.IProductDao;
  9 import com.shore.m2m.dao.impl.OrderDao;
 10 import com.shore.m2m.dao.impl.ProductDao;
 11 import com.shore.m2m.entity.Order;
 12 import com.shore.m2m.entity.OrderProductLink;
 13 import com.shore.m2m.entity.Product;
 14 
 15 /**
 16  * @author DSHORE/2020-3-17
 17  * 测试类
 18  */
 19 public class TestOrderDao {
 20     IOrderDao orderDao = new OrderDao();
 21     IProductDao productDao = new ProductDao();
 22     
 23     @Test //新增
 24     public void testAdd() {
 25         Order order = new Order();
 26         order.setNum("OM20200318002");
 27         order.setAddress("广东省广州市xxxxx");
 28         
 29         List<Product> products = new ArrayList<Product>();
 30         Product product = new Product();
 31         product.setName("oracle入门到精通");
 32         product.setPrice(99.99f);
 33         
 34         Product product2 = new Product();
 35         product2.setName("java入门到放弃");
 36         product2.setPrice(88.88f);
 37         
 38         products.add(product);
 39         products.add(product2);
 40         
 41         order.setProducts(products);
 42         
 43         //声明Order和Product实体间映射关系实例
 44         OrderProductLink opl = new OrderProductLink();
 45         opl.setOrder(order);
 46         opl.setProduct(product);
 47         
 48         OrderProductLink opl2 = new OrderProductLink();
 49         opl2.setOrder(order);
 50         opl2.setProduct(product2);
 51         
 52         //保存order表
 53         System.out.println(orderDao.addOrder(order));//返回值:1     说明插入数据成功
 54         //保存product表
 55         System.out.println(productDao.addProduct(product));//返回值:1
 56         System.out.println(productDao.addProduct(product2));//返回值:1
 57         //保存中间表product_orders
 58         System.out.println(orderDao.saveOrderProduct(opl));//返回值:1
 59         System.out.println(orderDao.saveOrderProduct(opl2));//返回值:1
 60     }
 61     
 62     @Test //更新(修改)
 63     public void testUpdate() {
 64         //之前104号商品对应51号订单;现在想改成对应53号订单;地址也改了
 65         Order order = new Order();
 66         order.setId(53);
 67         order.setAddress("北京市朝阳区xxxxxx");
 68         
 69         List<Product> products = new ArrayList<Product>();
 70         Product product = productDao.findByProductId(104);
 71         products.add(product);
 72         order.setProducts(products);
 73         
 74         //声明Order和Product实体间映射关系实例
 75         OrderProductLink opl = new OrderProductLink();
 76         opl.setOrder(order);
 77         opl.setProduct(product);
 78         
 79         System.out.println(orderDao.updateOrder(order));//返回值:1
 80         System.out.println(orderDao.updateOrderProduct(opl));//返回值:1
 81     }
 82     
 83     @Test //根据id查询:查询指定订单里面,有什么商品
 84     public void testFindById() {
 85         List<Order> orders = orderDao.findByOrderId(53);
 86         for (Order order : orders) {
 87             System.out.println(order.getProducts());
 88             /*返回值:
 89              * [com.shore.m2m.entity.Product@5bf0aecc]
 90              * [com.shore.m2m.entity.Product@1664023c]
 91              * [com.shore.m2m.entity.Product@7fcebc9f]
 92              * */
 93         }
 94     }
 95     
 96     @Test //查询所有(订单)
 97     public void testListAll() {
 98         List<Order> orders = orderDao.listAll();
 99         if (orders == null) {
100             System.out.println("orders is null。");
101         } else {
102             //System.out.println(orders.get(0));
103             for (Order o : orders) {
104                 System.out.println(o);
105                 /*返回值:
106                  * com.shore.m2m.entity.Order@561557c0
107                  * com.shore.m2m.entity.Order@13342a67
108                  * com.shore.m2m.entity.Order@45cbda0a
109                  * */
110             }
111         }
112     }
113     
114     @Test //删除订单(同时删除订单里面的所有商品)
115     public void testDeleteOrder() {
116         //假如前端要删除的订单:53
117         int id = 53;
118         //相当于获取前端指定订单中的所有商品
119         List<Order> orders = orderDao.findByOrderId(id);
120         List<Integer> ids = new ArrayList<Integer>();
121         for (Order o : orders) {
122             int i = 0;
123             if (i <= orders.size()) {//如果不加这个判断,会出现下标越界异常IndexOutOfBoundsException
124                 ids.add(o.getProducts().get(i++).getId());
125             }
126         }
127         //先解除中间表的关联关系
128         System.out.println("解除中间表的关联关系:" + orderDao.deleteOrderProduct(id));//返回值:解除中间表的关联关系:3
129         //删除商品
130         System.out.println(productDao.batchDeleteById(ids));//返回值:3   说明批量删除数据成功
131         //最后删除订单
132         System.out.println(orderDao.deleteOrder(id));//返回值:1 
133     }
134     
135     @Test //删除商品
136     public void testDeleteProduct() {
137         /**假如要删除106号商品
138          * 如果该订单里只有一件商品,那么连同该订单一起删除;
139          * 如果有多件商品,则删除指定的商品;
140          * 如果全部商品都删除,则也要连带订单一起删除。
141          */
142         int id = 106;
143         //根据商品id获取该订单里的商品件数(即:中间表一个订单号关联商品的个数)
144         Order order = orderDao.findOrderByProductId(id);
145         List<Order> orders = orderDao.findByOrderId(order.getId());
146         //如果该订单里只有一件商品,那么连同该订单一起删除
147         if (orders.size() == 1) {
148             //先解除中间表的关联关系(根据orders_id)
149             System.out.println(orderDao.deleteOrderProduct(order.getId()));//返回值:1
150             //删除商品
151             System.out.println(productDao.deleteProduct(id));//返回值:1   说明删除数据成功
152             //最后删除订单
153             System.out.println(orderDao.deleteOrder(order.getId()));//返回值:1
154         }else {
155             //先解除中间表的关联关系(根据product_id)
156             System.out.println(orderDao.deleteOrderProduct2(id));//返回值:1
157             //删除商品
158             System.out.println(productDao.deleteProduct(id));//返回值:1
159         }
160     }
161     
162     @Test // 批量删除 (删除商品)
163     public void testBatchDelete() {
164         List<Integer> ids = new ArrayList<Integer>();
165         ids.add(4);
166         ids.add(5);
167         ids.add(6);
168         System.out.println(productDao.batchDeleteById(ids));//返回值:3     说明批量删除数据成功
169     }
170 }

 

到此已完结!有任何问题,可留言。

mybatis 多对多关联的另一个版本:https://www.iteye.com/blog/nirvana1988-961770

 

 

mybatis单向一对一关联映射:https://www.cnblogs.com/dshore123/p/12489304.html
mybatis单向一对多关联映射:https://www.cnblogs.com/dshore123/p/12493450.html
mybatis单向多对多关联映射:https://www.cnblogs.com/dshore123/p/12526016.html

 

 

 

 

 

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/12526016.html

版权声明:欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

posted @ 2020-03-19 18:04  DSHORE  阅读(327)  评论(0编辑  收藏  举报