语法糖

  1. <sql id="colums">
  2. person_id, name, gender, person_addr, birthday
  3. </sql>
  4. <select id="selectPersonAll" resultMap="">
  5. select <include refid="colums" /> from person
  6. </select>
  1. // parameterType 可以使用别名,int 可以代替java.lang.Integer ,
  2. // map 可以代替 java.lang.Map , 其他自定义类,必须通过mybatis配置文件,配置别名使用
  3. <update id="update" parameterType="com.rl.model1.Person">
  4. update person t
  5. <set>
  6. <if test="name != null">
  7. t.name = #{name},
  8. </if>
  9. <if test="gender != null">
  10. t.gender = #{gender},
  11. </if>
  12. <if test="person_addr != null">
  13. t.person_addr = #{person_addr},
  14. </if>
  15. </set>
  16. where t.person_id = #{personId}
  17. </update>
  18. <update id="updateWhere" parameterType="com.rl.model1.Person">
  19. update person t set
  20. t.name = #{name},
  21. t.gender = #{gender}
  22. t.person_addr = #{personAddr}
  23. where t.person_id = #{personId}
  24. </update>
  1. <!-- mysql 删除不可以用别名 -->
  2. <delete id="enumerationDelete" parameterType="enumeration">
  3. delete from enumeration_list where enumId = #{enumId}
  4. </delete>
  5. <!-- 批量删除,只能少量数据,大数据会溢出 -->
  6. <delete id="enumerationDeleteMap" parameterType="Map">
  7. delete from enumeration_list where enumId in
  8. <foreach collection="ids" open="(" close=")" item="enumId" separator="," index="index">
  9. #{enumId}
  10. </foreach>
  11. </delete>
  1. <insert id="enumerationInsert" parameterType="enumeration">
  2. <!--
  3. selectKey 是做主键返回的
  4. keyProperty 接受主键返回的属性
  5. order: "AFTER" 是mysql中使用的 "BEFORE" 指的是顺序,生成主键的顺序 自增序列
  6. resultType 返回主键的数据类型
  7. 生成主键的sql select LAST_INSERT_ID()
  8. -->
  9. <selectKey keyProperty="enumId" order="AFTER" resultType="java.lang.Integer">
  10. <!-- 此处是mysql的写法,oracle中不一样 -->
  11. select LAST_INSERT_ID()
  12. </selectKey>
  13. insert into enumeration_list (enumId, typeId, name, parentId)
  14. values
  15. <foreach collection="enumList" separator="," item="enum">
  16. (#{enum.enumId}, #{enum.typeId}, #{enum.name}, #{enum.parentId})
  17. </foreach>
  18. </insert>
  19. <insert id="enumerationInsert" parameterType="enumeration">
  20. <!--
  21. selectKey 是做主键返回的
  22. keyProperty 接受主键返回的属性
  23. order: "AFTER" 是mysql中使用的 "BEFORE" 指的是顺序,生成主键的顺序 自增序列
  24. resultType 返回主键的数据类型
  25. 生成主键的sql select LAST_INSERT_ID()
  26. -->
  27. <selectKey keyProperty="enumId" order="AFTER" resultType="java.lang.Integer">
  28. <!-- 此处是mysql的写法,oracle中不一样 -->
  29. select LAST_INSERT_ID()
  30. </selectKey>
  31. insert into enumeration_list (enumId, typeId, name, parentId)
  32. value(#{enumId}, #{typeId}, #{name}, #{parentId})
  33. </insert>
  1. ### 转义语法 ###
  2. <![CDATA[
  3. select * from user u where u.datetime > #{date}
  4. ]]>
  5. ### parameterType的用法,可以是包装类型与任意Class,Map , 通过getUserId方法获取值的 ###
  6. <select id="userSelectOne" parameterType="com.lijunyang.model.user" resultMap="user">
  7. <![CDATA[
  8. select * from user u where u.datetime > #{datatime}
  9. ]]>
  10. </select>
  11. <select id="userSelectOne" parameterType="java.util.Map" resultMap="user">
  12. select * from PersonTest2 p where p.name like '%${name}%'
  13. </select>
  14. <select id="enumerationSelectMap" parameterType="java.util.Map" resultMap="enumeration">
  15. select * from enumeration_list e
  16. <where>
  17. <if test="enumId != null">
  18. e.enumId = #{enumId}
  19. </if>
  20. <if test="typeId != null">
  21. and e.typeId = #{typeId}
  22. </if>
  23. <if test="name != null">
  24. and e.name = #{name}
  25. </if>
  26. <if test="parentId != null">
  27. and e.parentId = #{parentId}
  28. </if>
  29. </where>
  30. </select>
  31. <select id="enumerationMap" parameterType="Map">
  32. select * from enumeration_list where enumId in
  33. <foreach collection="ids" open="(" close=")" item="enumId" separator="," index="index">
  34. #{enumId}
  35. </foreach>
  36. </select>

一对一

一个班主任只属于一个班级,一个班级也只能有一个班主任
select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=1

classObj = SELECT FROM class WHERE c_id = 1;
SELECT
FROM teacher WHERE t_id = 1; //1 是上一个查询得到的teacher_id的值

表设计,使用MYSQL

  1. CREATE TABLE IF NOT EXISTS `class_list` (
  2. `c_id` int(18) UNSIGNED NOT NULL AUTO_INCREMENT,
  3. `c_name` varchar(255) NOT NULL,
  4. `t_id` int(18) UNSIGNED NOT NULL,
  5. PRIMARY KEY (`c_id`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  7. CREATE TABLE IF NOT EXISTS `teacher_list` (
  8. `t_id` int(18) UNSIGNED NOT NULL AUTO_INCREMENT,
  9. `t_name` varchar(255) NOT NULL,
  10. PRIMARY KEY (`t_id`)
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  12. SET FOREIGN_KEY_CHECKS=0;
  13. alter table class_list add constraint `FK_TEACHERID` foreign key(`t_id`) references teacher_list(`t_id`);
  14. SET FOREIGN_KEY_CHECKS=1;
  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. <!-- 为这个mapper指定一个唯一的namespace,namespace的值习惯上设置成包名+sql映射文件名,这样保证了namespace的值是唯一的-->
  5. <mapper namespace="com.yc.mybatis.test.classMapper">
  6. <!--
  7. 方式一:嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集
  8. 封装联表查询的数据(去除重复的数据)
  9. select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=1
  10. -->
  11. <select id="getClass" parameterType="int" resultMap="getClassMap">
  12. select * from class c, teacher t where c.teacher_id = t.t_id and c.teacher_id=#{id}
  13. </select>
  14. <!-- resultMap:映射实体类和字段之间的一一对应的关系 -->
  15. <resultMap type="Classes" id="getClassMap">
  16. <id property="id" column="c_id"/>
  17. <result property="name" column="c_name"/>
  18. <association property="teacher" javaType="Teacher">
  19. <id property="id" column="t_id"/>
  20. <result property="name" column="t_name"/>
  21. </association>
  22. </resultMap>
  23. <!--
  24. 方式二:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型
  25. SELECT * FROM class WHERE c_id=1;
  26. SELECT * FROM teacher WHERE t_id=1 //1 是上一个查询得到的teacher_id的值
  27. property:别名(属性名) column:列名 -->
  28. <!-- 把teacher的字段设置进去 -->
  29. <select id="getClass1" parameterType="int" resultMap="getClassMap1">
  30. select * from class where c_id=#{id}
  31. </select>
  32. <resultMap type="Classes" id="getClassMap1">
  33. <id property="id" column="c_id"/>
  34. <result property="name" column="c_name"/>
  35. <association property="teacher" column="teacher_id" select="getTeacher"/>
  36. </resultMap>
  37. <select id="getTeacher" parameterType="int" resultType="Teacher">
  38. select t_id id,t_name name from teacher where t_id =#{id}
  39. </select>
  40. </mapper>
property 对象属性的名称
javaType 对象属性的类型
column 所对应的外键字段名称
select 使用另一个查询封装的结果

一对多 and 多对一

一个顾客对应多个订单,而一个订单只能对应一个客户。
一个订单对应多个商品
1表示当前的orderId

  1. CREATE TABLE `user` (
  2. `userId` int(18) unsigned NOT NULL,
  3. `userName` varchar(255) NOT NULL,
  4. `password` varchar(255) NOT NULL,
  5. `Telephone` varchar(255) DEFAULT NULL,
  6. `email` varchar(255) DEFAULT '',
  7. `createTime` datetime NOT NULL,
  8. `updatePasswordTime` datetime NOT NULL,
  9. PRIMARY KEY (`userId`),
  10. UNIQUE KEY `userName` (`userName`)
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8
  12. CREATE TABLE `goods_list` (
  13. `goodsId` int(18) unsigned NOT NULL AUTO_INCREMENT,
  14. `goodsName` varchar(255) NOT NULL,
  15. `goodsPrice` double(11,2) NOT NULL,
  16. `goodsUnit` varchar(255) NOT NULL,
  17. `goodsIntroduce` varchar(255) DEFAULT '',
  18. `pathId` int(18) NOT NULL,
  19. `classType` int(18) DEFAULT NULL,
  20. PRIMARY KEY (`goodsId`)
  21. ) ENGINE=InnoDB DEFAULT CHARSET=utf8
  22. CREATE TABLE IF NOT EXISTS `order_list` (
  23. `orderId` int(18) UNSIGNED NOT NULL AUTO_INCREMENT,
  24. `orderStartTime` datetime NOT NULL,
  25. `orderEndTime` datetime,
  26. `orderTotalPrice` double(11,2) NOT NUll,
  27. `userId` int(18) UNSIGNED NOT NULL,
  28. `orderGoodsListNum` int(18) UNSIGNED NOT NULL,
  29. PRIMARY KEY (`orderId`)
  30. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  31. alter table order_list add constraint `FK_ORDERID`
  32. foreign key(`userId`) references user(`userId`);
  33. CREATE TABLE `order_goods_list` (
  34. `orderId` int(18) UNSIGNED NOT NULL,
  35. `goodsId` int(18) UNSIGNED NOT NULL,
  36. `goodsCount` int(18) UNSIGNED NOT NULL,
  37. `goodsTotalPrice` double(11,2) NOT NULL
  38. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  39. alter table order_goods_list add constraint `FK_ORDERID_GOODS`
  40. foreign key(`orderId`) references order_list(`orderId`);
  41. alter table order_goods_list add constraint `FK_GOODSID`
  42. foreign key(`goodsId`) references goods_list(`goodsId`);
  1. select * from user;

image.png

  1. select * from goods_list;

image.png

  1. INSERT INTO `order_list` (orderStartTime, orderTotalPrice, userId, orderGoodsListNum)
  2. VALUES ('2019-03-18 16:12:34', 10.0, 10010, 10);
  3. select * from order_goods_list ol;
  4. select * from order_goods_list ol where ol.orderId = 1;
  5. update order_list set orderTotalPrice = 310.00 where orderId = 1;
  6. update order_list set orderTotalPrice = 310.00, orderGoodsListNum = 30 where orderId = 1;

image.png

  1. INSERT INTO `order_goods_list` (orderId, goodsId, goodsCount, goodsTotalPrice)
  2. VALUES (1, 29, 10, 1.0);
  3. INSERT INTO `order_goods_list` (orderId, goodsId, goodsCount, goodsTotalPrice)
  4. VALUES (1, 30, 10, 10.0);
  5. INSERT INTO `order_goods_list` (orderId, goodsId, goodsCount, goodsTotalPrice)
  6. VALUES (1, 31, 10, 10.0);
  7. INSERT INTO `order_goods_list` (orderId, goodsId, goodsCount, goodsTotalPrice)
  8. VALUES (1, 32, 10, 10.0);
  9. select * from order_goods_list;
  10. select * from order_goods_list ogl where ogl.orderId = 1;
  11. select * from order_goods_list ol where ol.orderId = 1 limit 0,3;

image.png

image.png

  1. select * from order_list o, order_goods_list ol where o.orderId = 1 and o.orderId = ol.orderId;

image.png

  1. ## 包含 in
  2. select * from goods_list where goodsId in (29, 30, 31, 32);
  3. ## between and 在什么什么之间
  4. select * from goods_list where goodsId between 29 and 32;
  5. ## is
  6. select * from goods where classType is (not) NULL
  7. select * from goods_list where classType is not NUll;
  8. select * from goods_list where classType is NUll;

image.png

  1. #select distinct 字段名 from 表名;字段名表示要过滤重复记录的字段

image.png

  1. ## like %
  2. ## % 表示匹配任意字符
  3. ## _ 表示匹配单个字符
  4. #### 如果需要查询带有 % 或 _ 的数据,由于 % 和 _ 是通配符,则需要使用 \ 进行转义
  5. ## \% 表示 %,\_ 表示 _
  6. ## and(&&) 有时在查询时为了查询结果更加精确,需要多个限条件,这时就需要 and(&&) 来连接条件
  7. ## or(||) 有时在查询时,只需要数据满足某些条件中的某一个,这时就需要使用 or(||) 来连接条件
  8. select * from user where userName like 'lijunyang%';
  1. ### count()函数:统计记录条数 select count(记录) from 表名
  2. select count(userId) from user;
  3. ### sum()函数:计算表中某个字段值的总和,select sum(字段名) from 表名
  4. ### avg()函数:计算表中某个字段的平均值 select avg(字段名) from 表名
  5. ### max()函数:返回表中某个字段中的最大值
  6. ### min()函数:返回表中某个字段中的最小值

image.png image.png

  1. ### 在对数据表中的数据进行统计时,需要将数据按照一定的特征分组统计,此时就需
  2. ### 要使用分组查询 select 查询内容 from 表名 group by 分组依据 [having表达式条件]
  3. ### select 查询内容 from 表名 order by 排序条件 asc/desc,asc表示升序 desc表示降序
  4. ### 分页查询 select 查询内容 from 表名 limit 偏移量m,记录数n
  5. where having
  6. where having关键字都用于设置条件表达式对查询结果进行过滤,区别是having后面可以跟聚合
  7. 函数,而where不能,通常having关键字都与group by 一起使用,表示对分组后的数据进行过滤

image.png

private List orders;

最终一对多select语句

分为几种查询方式:sql查询,一次性查出所有关联信息用下面的语句

  1. select * from order_list o, order_goods_list ogl, goods_list ol where
  2. o.orderId = 1 and
  3. o.orderId = ogl.orderId and
  4. ol.goodsId in
  5. (select goodsId from order_goods_list where orderId = o.orderId) limit 0,3
  6. ## 查询表格型数据,与下面的面向对象型不一样

image.png

在实际工作中,配合ORM框架配置,如Mybatis等,查询要分为2次查询

  1. ## 首先查询订单信息
  2. select * from order_list where orderId = #{orderId}
  3. ## 在查询订单id关联的所有商品信息
  4. select * from order_goods_list ogl, goods_list ol where ogl.orderId = #{orderId} and ol.goodsId = ogl.goodsId
  5. ## 最好在将数据合并,就是一份面向对象结构的数据了

注意事项

注意,此种设计只为了学习使用,实际场景中可以使用冗余字段,将order_goods_list,包含goods_list的所有字段,形成冗余,这样只需要查询2张表即可

Goods 商品类 : 映射商品表

  1. package com.lijunyang.model;
  2. /**
  3. * 商品类
  4. * 商品名称
  5. * 商品ID
  6. * 商品价格
  7. * 商品单位
  8. * 商品介绍
  9. * 商品图片路径ID
  10. * */
  11. public class Goods {
  12. private String goodsName;
  13. private Integer goodsId;
  14. private Double goodsPrice;
  15. private String goodsUnit;
  16. private String goodsIntroduce;
  17. private Integer pathId;
  18. private FileSavePath filePath;
  19. private Integer classType;
  20. private Enumeration enumeration;
  21. public Integer getClassType() {
  22. return classType;
  23. }
  24. public void setClassType(Integer classType) {
  25. this.classType = classType;
  26. }
  27. public Enumeration getEnumeration() {
  28. return enumeration;
  29. }
  30. public void setEnumeration(Enumeration enumeration) {
  31. this.enumeration = enumeration;
  32. }
  33. public Integer getPathId() {
  34. return pathId;
  35. }
  36. public void setPathId(Integer pathId) {
  37. this.pathId = pathId;
  38. }
  39. public String getGoodsName() {
  40. return goodsName;
  41. }
  42. public void setGoodsName(String goodsName) {
  43. this.goodsName = goodsName;
  44. }
  45. public Integer getGoodsId() {
  46. return goodsId;
  47. }
  48. public void setGoodsId(Integer goodsId) {
  49. this.goodsId = goodsId;
  50. }
  51. public Double getGoodsPrice() {
  52. return goodsPrice;
  53. }
  54. public void setGoodsPrice(Double goodsPrice) {
  55. this.goodsPrice = goodsPrice;
  56. }
  57. public String getGoodsUnit() {
  58. return goodsUnit;
  59. }
  60. public void setGoodsUnit(String goodsUnit) {
  61. this.goodsUnit = goodsUnit;
  62. }
  63. public String getGoodsIntroduce() {
  64. return goodsIntroduce;
  65. }
  66. public void setGoodsIntroduce(String goodsIntroduce) {
  67. this.goodsIntroduce = goodsIntroduce;
  68. }
  69. public FileSavePath getFilePath() {
  70. return filePath;
  71. }
  72. public void setFilePath(FileSavePath filePath) {
  73. this.filePath = filePath;
  74. }
  75. @Override
  76. public String toString() {
  77. return "Goods{" +
  78. "goodsName='" + goodsName + '\'' +
  79. ", goodsId=" + goodsId +
  80. ", goodsPrice=" + goodsPrice +
  81. ", goodsUnit='" + goodsUnit + '\'' +
  82. ", goodsIntroduce='" + goodsIntroduce + '\'' +
  83. ", pathId=" + pathId +
  84. ", filePath=" + filePath +
  85. ", classType=" + classType +
  86. ", enumeration=\n" + enumeration +
  87. '}';
  88. }
  89. }

OrderGoods类 订单商品表 : 映射订单商品表

  1. package com.lijunyang.model;
  2. import java.util.List;
  3. /**
  4. * 订单商品类
  5. * 订单ID
  6. * 商品
  7. * 商品数量
  8. * 商品价格
  9. * */
  10. public class OrderGoods {
  11. private Integer orderId;
  12. private List<Goods> goodsList;
  13. private Integer goodsCount;
  14. private Double goodsTotalPrice;
  15. public Integer getOrderId() {
  16. return orderId;
  17. }
  18. public void setOrderId(Integer orderId) {
  19. this.orderId = orderId;
  20. }
  21. public List<Goods> getGoodsList() {
  22. return goodsList;
  23. }
  24. public void setGoodsList(List<Goods> goodsList) {
  25. this.goodsList = goodsList;
  26. }
  27. public Integer getGoodsCount() {
  28. return goodsCount;
  29. }
  30. public void setGoodsCount(Integer goodsCount) {
  31. this.goodsCount = goodsCount;
  32. }
  33. public Double getGoodsTotalPrice() {
  34. return goodsTotalPrice;
  35. }
  36. public void setGoodsTotalPrice(Double goodsTotalPrice) {
  37. this.goodsTotalPrice = goodsTotalPrice;
  38. }
  39. @Override
  40. public String toString() {
  41. return "OrderGoods{" +
  42. "orderId=" + orderId +
  43. ", goodsList=" + goodsList +
  44. ", goodsCount=" + goodsCount +
  45. ", goodsTotalPrice=" + goodsTotalPrice +
  46. '}';
  47. }
  48. }

OrderGoods类的mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.lijunyang.mapper.orderGoodsMapper">
  6. <resultMap type="orderGoods" id="orderGoods">
  7. <id column="orderId" property="orderId" />
  8. <result column="goodsCount" property="goodsCount"/>
  9. <result column="goodsTotalPrice" property="goodsTotalPrice"/>
  10. <collection property="goodsList" javaType="ArrayList" ofType="com.lijunyang.model.Goods">
  11. <id column="goodsId" property="goodsId" />
  12. <result column="goodsName" property="goodsName"/>
  13. <result column="goodsPrice" property="goodsPrice"/>
  14. <result column="goodsUnit" property="goodsUnit"/>
  15. <result column="goodsIntroduce" property="goodsIntroduce"/>
  16. <result column="pathId" property="pathId"/>
  17. <result column="classType" property="classType"/>
  18. <association property="filePath" javaType="com.lijunyang.model.FileSavePath">
  19. <result column="fileId" property="fileId" />
  20. <result column="path" property="path"/>
  21. </association>
  22. <association property="enumeration" javaType="com.lijunyang.model.Enumeration">
  23. <result column="enumId" property="enumId" />
  24. <result column="typeId" property="typeId"/>
  25. <result column="parentId" property="parentId"/>
  26. <result column="name" property="name"/>
  27. </association>
  28. </collection>
  29. </resultMap>
  30. <select id="orderGoodsSelectMap" parameterType="java.util.Map" resultMap="orderGoods">
  31. select * from goods_list gl, order_goods_list ogl ,fileSavePath f, enumeration_list e
  32. <where>
  33. ogl.orderId = #{orderId}
  34. and ogl.goodsId = gl.goodsId
  35. and gl.pathId = f.fileId
  36. and e.enumId = gl.classType
  37. </where>
  38. </select>
  39. <select id="orderGoodsSelectPagesMap" parameterType="java.util.Map" resultMap="orderGoods">
  40. select * from goods_list gl, order_goods_list ogl ,fileSavePath f, enumeration_list e
  41. <where>
  42. ogl.orderId = #{orderId}
  43. and ogl.goodsId = gl.goodsId
  44. and gl.pathId = f.fileId
  45. and e.enumId = gl.classType
  46. </where>
  47. limit #{page},#{pageSize}
  48. </select>
  49. <select id="orderGoodsSelectPagesThreeMap" parameterType="java.util.Map" resultMap="orderGoods">
  50. select * from goods_list gl, order_goods_list ogl ,fileSavePath f, enumeration_list e
  51. <where>
  52. ogl.orderId = #{orderId}
  53. and ogl.goodsId = gl.goodsId
  54. and gl.pathId = f.fileId
  55. and e.enumId = gl.classType
  56. </where>
  57. limit 0, 3
  58. </select>
  59. </mapper>

OrderGoods junit 单元测试

  1. package com.lijunyang.test;
  2. import com.lijunyang.model.Order;
  3. import com.lijunyang.model.OrderGoods;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import java.io.InputStream;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. public class OrderGoodsDaoTest {
  15. SqlSessionFactory sessionFactory;
  16. @Before
  17. public void setUp() throws Exception {
  18. InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
  19. sessionFactory = new SqlSessionFactoryBuilder().build(in);
  20. //注册接口类
  21. sessionFactory.getConfiguration().addMapper(Order.class);
  22. }
  23. @Test
  24. public void select() {
  25. // 创建SqlSession
  26. SqlSession session = sessionFactory.openSession();
  27. try {
  28. Map<String, Object> map = new HashMap<String, Object>();
  29. map.put("orderId", 1);
  30. List<OrderGoods> list = session.selectList("com.lijunyang.mapper.orderGoodsMapper.orderGoodsSelectMap", map);
  31. for (OrderGoods o : list) {
  32. System.out.println(o);
  33. }
  34. } finally {
  35. session.close();
  36. }
  37. }
  38. @Test
  39. public void selectPages() {
  40. // 创建SqlSession
  41. SqlSession session = sessionFactory.openSession();
  42. try {
  43. Map<String, Object> map = new HashMap<String, Object>();
  44. map.put("orderId", 1);
  45. map.put("page", 0);
  46. map.put("pageSize", 3);
  47. List<OrderGoods> list = session.selectList("com.lijunyang.mapper.orderGoodsMapper.orderGoodsSelectPagesMap", map);
  48. for (OrderGoods o : list) {
  49. System.out.println(o);
  50. }
  51. } finally {
  52. session.close();
  53. }
  54. }
  55. }

Order类 订单类 : 映射订单表

  1. package com.lijunyang.model;
  2. import java.util.Date;
  3. import java.util.List;
  4. /**
  5. * 订单商品类
  6. * 订单ID
  7. * 用户ID
  8. * 订单开始时间
  9. * 确认订单时间
  10. * 商品总数量
  11. * 商品总价格
  12. 当用户点击下单时,orderStartTime 赋值,此时允许用户修改订单
  13. 当用户点击确认订单时,orderEndTime 赋值,此时不在允许用户修改订单
  14. 可以通过userId获取到用户未确认的订单,只允许有一个未确认订单
  15. * */
  16. public class Order {
  17. private Integer orderId;
  18. private Integer userId;
  19. private Date orderStartTime;
  20. private Date orderEndTime;
  21. private Integer orderGoodsListNum;
  22. private Double orderTotalPrice;
  23. private OrderGoods OrderGoods;
  24. public Integer getOrderId() {
  25. return orderId;
  26. }
  27. public void setOrderId(Integer orderId) {
  28. this.orderId = orderId;
  29. }
  30. public Integer getUserId() {
  31. return userId;
  32. }
  33. public void setUserId(Integer userId) {
  34. this.userId = userId;
  35. }
  36. public Date getOrderStartTime() {
  37. return orderStartTime;
  38. }
  39. public void setOrderStartTime(Date orderStartTime) {
  40. this.orderStartTime = orderStartTime;
  41. }
  42. public Date getOrderEndTime() {
  43. return orderEndTime;
  44. }
  45. public void setOrderEndTime(Date orderEndTime) {
  46. this.orderEndTime = orderEndTime;
  47. }
  48. public Integer getOrderGoodsListNum() {
  49. return orderGoodsListNum;
  50. }
  51. public void setOrderGoodsListNum(Integer orderGoodsListNum) {
  52. this.orderGoodsListNum = orderGoodsListNum;
  53. }
  54. public Double getOrderTotalPrice() {
  55. return orderTotalPrice;
  56. }
  57. public void setOrderTotalPrice(Double orderTotalPrice) {
  58. this.orderTotalPrice = orderTotalPrice;
  59. }
  60. public com.lijunyang.model.OrderGoods getOrderGoods() {
  61. return OrderGoods;
  62. }
  63. public void setOrderGoods(com.lijunyang.model.OrderGoods orderGoods) {
  64. OrderGoods = orderGoods;
  65. }
  66. @Override
  67. public String toString() {
  68. return "Order{" +
  69. "orderId=" + orderId +
  70. ", userId=" + userId +
  71. ", orderStartTime=" + orderStartTime +
  72. ", orderEndTime=" + orderEndTime +
  73. ", orderGoodsListNum=" + orderGoodsListNum +
  74. ", orderTotalPrice=" + orderTotalPrice +
  75. ", OrderGoods=" + OrderGoods +
  76. '}';
  77. }
  78. }

Order类的mapper

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.lijunyang.mapper.orderMapper">
  6. <resultMap type="order" id="order">
  7. <id column="orderId" property="orderId" />
  8. <result column="userId" property="userId"/>
  9. <result column="orderStartTime" property="orderStartTime"/>
  10. <result column="orderEndTime" property="orderEndTime"/>
  11. <result column="orderGoodsListNum" property="orderGoodsListNum"/>
  12. <result column="orderTotalPrice" property="orderTotalPrice"/>
  13. <association property="orderGoods"
  14. javaType="com.lijunyang.model.OrderGoods"
  15. column="orderId"
  16. select="com.lijunyang.mapper.orderGoodsMapper.orderGoodsSelectPagesThreeMap"/>
  17. </resultMap>
  18. <select id="orderIdSelectMap" parameterType="java.util.Map" resultMap="order">
  19. select * from order_list o
  20. <where>
  21. o.orderId = #{orderId}
  22. </where>
  23. </select>
  24. <select id="orderSelectMap" parameterType="java.util.Map" resultMap="order">
  25. select * from order_list o
  26. </select>
  27. </mapper>

Order junit 单元测试

  1. package com.lijunyang.test;
  2. import com.lijunyang.model.Enumeration;
  3. import com.lijunyang.model.Order;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import org.junit.Before;
  9. import org.junit.Test;
  10. import java.io.InputStream;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. public class OrderDaoTest {
  15. SqlSessionFactory sessionFactory;
  16. @Before
  17. public void setUp() throws Exception {
  18. InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
  19. sessionFactory = new SqlSessionFactoryBuilder().build(in);
  20. //注册接口类
  21. sessionFactory.getConfiguration().addMapper(Order.class);
  22. }
  23. @Test
  24. public void select() {
  25. // 创建SqlSession
  26. SqlSession session = sessionFactory.openSession();
  27. try {
  28. Map<String, Object> map = new HashMap<String, Object>();
  29. map.put("orderId", 1);
  30. List<Order> list = session.selectList("com.lijunyang.mapper.orderMapper.orderSelectMap", map);
  31. for (Order o : list) {
  32. System.out.println(o);
  33. }
  34. } finally {
  35. session.close();
  36. }
  37. }
  38. }

多对多

上面的表设计中,商品表,订单商品表,订单表
其中商品表与订单表的关系是, 多对多,因为,订单商品表与商品表在结构上是多对多
订单表与订单商品表的关系是,一对多
通过中间表,订单商品表维护他们之间的关系

商品表,多个商品会重复对应多条订单
image.png

订单表,这里只有一条,假设有多条的情况,如何和商品表相互对应,多条订单会重复对应多个商品
image.png

中间表(关系表)
image.png

还有一个例子是

多对多关系处理:
通过学生选课了解多对多问题的处理:
mybatis 一对一,一对多,多对多 - 图16

在多对多中在一个表中添加一个字段就行不通了,所以处理多对多表问题时,就要考虑建立关系表了
例:
学生表:mybatis 一对一,一对多,多对多 - 图17

课程表:mybatis 一对一,一对多,多对多 - 图18

关系表:mybatis 一对一,一对多,多对多 - 图19**

注:所以对于多对多表,通过关系表就建立起了两张表的联系!多对多表时建立主外键后,要先删除约束表内容再删除主表内容