Mybatis 多表映射基於XML總結(一對一,一對多,多對多)


一、數據表

數據包括訂單,產品,游客,會員。

1.1數據說明和數據關系:

產品表說明:

訂單表說明:

會員表說明

旅客表說明

數據表的ER圖

ER圖

表與表之間的業務關系

旅客表(traverller)、訂單表(orders)、會員表(member)、產品表(product)的id都是uuid()下隨機生成的

  • 訂單表(orders)->產品表(product)一對一的關系
  • 訂單表(orders)->會員表(member)    一對一的關系
  • 訂單表(orders)->旅客表(traverller)多對多的關系(在Mybatis時中和一對多的處理很像,只不過多對多需要一張中間表)

二、實體類建立

Product實體類:

package domain;

import org.springframework.format.annotation.DateTimeFormat;
import util.DateUtils;

import java.io.Serializable;
import java.util.Date;

public class Product implements Serializable {

    private String id; // 主鍵
    private String productNum; // 編號 唯一
    private String productName; // 名稱
    private String cityName; // 出發城市
    //這個注解的目的是用spring來幫助處理這個屬性從表單提交時的數據轉換
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
    private Date departureTime; // 出發時間
    private String departureTimeStr;//出發時間格式化數據
    private double productPrice; // 產品價格
    private String productDesc; // 產品描述
    private Integer productStatus; // 狀態 0 關閉 1 開啟
    private String productStatusStr;//狀態格式化

    //省略getter 和 setter 
}

Member實體類:

package domain;

import java.io.Serializable;

public class Member implements Serializable {
    private String id;
    private String name;
    private String nickname;
    private String phoneNum;
    private String email;

    //省略getter 和 setter 
}

Traveller實體類:

package domain;

import java.io.Serializable;

public class Traveller implements Serializable {
    private String id;
    private String name;
    private String sex;
    private String phoneNum;
    private Integer credentialsType;
    private String credentialsTypeStr;
    private String credentialsNum;
    private Integer travellerType;
    private String travellerTypeStr;

    //省略getter 和 setter 
    
}

Orders實體類:

package domain;

import org.springframework.format.annotation.DateTimeFormat;
import util.DateUtils;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class Orders implements Serializable {

    private String id;
    private String orderNum;
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm")
    private Date orderTime;
    private String orderTimeStr; //訂單時間格式化
    private int orderStatus;
    private String orderStatusStr; //訂單狀態格式化
    private int peopleCount;
    private Product product;
    private List<Traveller> travellers;
    private Member member;
    private Integer payType;
    private String payTypeStr; //支付狀態格式化
    private String orderDesc;

 //省略getter 和 setter 

}

 

三、DAO層建立

使用Mybatis的動態代理,因此不需要自己實現DAO,因此要對DAO進行配置

IMemberDao接口:

package dao;

import domain.Member;

public interface IMemberDao {

    Member findMemberById(String id);
}

IProductDao接口:

package dao;

import domain.Product;

import java.util.List;

public interface IProductDao {

    //查詢所有商品信息
    List<Product> findAll() throws Exception;

    void insert(Product product) throws Exception;

    Product findById(String id);
}

ITravellerDao接口:

package dao;

import domain.Traveller;

import java.util.List;

public interface ITraveller {

    /**
     * 根據訂單查詢旅客信息
     * @param id
     * @return
     */
    List<Traveller> findTravellerByOrderId(String id);

}

IOrderDao接口:

package dao;
import domain.Orders;
import java.util.List;

public interface IOrdersDao {

    /**
     * 嵌套查詢全部信息
     * 包括旅客信息,會員信息,產品信息
     * @return
     * @throws Exception
     */
    List<Orders> findAll() throws Exception;

    /**
     * 嵌套結果查詢全部
     * 包括旅客信息,會員信息,產品信息
     * @return
     * @throws Exception
     */
    List<Orders> findAll1() throws Exception;

    /**
     * 只查詢訂單
     * 不包括旅客信息,會員信息,產品信息
     * @return
     * @throws Exception
     */
    List<Orders> getAll() throws Exception;

    /**
     * 根據ID查詢訂單
     * 包括旅客信息,會員信息,產品信息
     * @param id
     * @return
     * @throws Exception
     */
    Orders findById(String id) throws Exception;
}

基於XML配置Mybatis

1、配置全局配置文件:

<?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>
    <!--使用typeAlias配置別名-->
    <typeAliases>
        <!--type指定全限定類名,alias指定別名,別名不區分大小寫-->
        <typeAlias type="domain.Product" alias="product"/>
        <typeAlias type="domain.Orders" alias="orders"/>
        <typeAlias type="domain.Member" alias="member"/>
        <typeAlias type="domain.Traveller" alias="traveller"/>
    </typeAliases>
    <!--這個mapper必須在最下面!! 映射dao的配置文件-->
    <mappers>
        <mapper resource="dao/ProductMapper"/>
        <mapper resource="dao/OrderMapper"/>
        <mapper resource="dao/MemberMapper"/>
        <mapper resource="dao/TravellerMapper"/>
    </mappers>
</configuration>

這里沒有配置數據源信息的原因是已經在spring中配置了

2、將mybatis工廠對象交給Spring IOC容器管理

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--開啟注解掃描,只需要掃描Service層的注解即可,DAO層由xml配置-->
<!--    <context:component-scan base-package="dao"/>-->
    <context:component-scan base-package="service"/>


    <!--Spring整合mybatis-->
    <!--配置連接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入數據庫連接信息-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm1?use Unicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--配置sqlSession工廠對象-->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">     
        <!--設置數據源-->
        <property name="dataSource" ref="dataSource"/>
        <!--映射mybatis全局配置文件-->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"/>
    </bean>

    <!-- 配置Spring的聲明式事務管理 -->
    <!-- 配置事務管理器 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--映射mapper文件,獲取生成代理Dao-->
    <bean id="productMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="dao.IProductDao"/>
        <property name="sqlSessionFactory" ref="factory"/>
    </bean>
    <bean id="orderMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="dao.IOrdersDao"/>
        <property name="sqlSessionFactory" ref="factory"/>
    </bean>



</beans>

3、配置每個DAO接口的Mapper文件

3.1MemberMapper

<?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="dao.IMemberDao">
    <select id="findMemberById" resultType="domain.Member">
        select * from member where id = #{id}
    </select>
</mapper>

3.2ProductMapper

<?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="dao.IProductDao">
    <select id="findAll" resultType="product">
        select * from product
    </select>
    <insert id="insert" parameterType="product">
        <selectKey keyProperty="id" keyColumn="id" resultType="java.lang.String" order="BEFORE">
            select replace(uuid(),'-','')
        </selectKey>
        insert into product(id,productNum,productName,departureTime,cityName,productPrice,productDesc,productStatus)
         values (#{id},#{productNum},#{productName},#{departureTime},#{cityName},#{productPrice},#{productDesc},#{productStatus})
    </insert>
    <select id="findById" resultType="product" parameterType="java.lang.String">
        select * from product where id = #{id}
    </select>
</mapper>

3.3TravellerMapper

<?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="dao.ITraveller">
    <select id="findTravellerByOrderId" resultType="traveller" parameterType="java.lang.String">
        select * from traveller where id in (select travellerId from order_traveller where #{oid} = orderId)
    </select>
</mapper>

3.4OrderMapper

<?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="dao.IOrdersDao">
    <!--嵌套結果查詢-->
    <resultMap id="orderMap" type="domain.Orders">
        <id property="id" column="oid"/>
        <result property="orderNum" column="orderNum"/>
        <result property="orderTime" column="orderTime"/>
        <result property="orderStatus" column="orderStatus"/>
        <result property="peopleCount" column="peopleCount"/>
        <result property="payType" column="payType"/>
        <result property="orderDesc" column="orderDesc"/>
        <!--association:用於映射關聯查詢單個對象的信息
           property:要將關聯查詢的用戶信息映射到Orders中那個屬性-->
        <association property="product" javaType="domain.Product">
            <!-- id:關聯查詢的唯一標識
                column:指定唯一標識信息的列
                property:映射到product的哪個屬性
            -->
            <id column="pid" property="id"/>
            <result column="productNum" property="productNum"/>
            <result column="productName" property="productName"/>
            <result column="cityName" property="cityName"/>
            <result column="departureTime" property="departureTime"/>
            <result column="productPrice" property="productPrice"/>
            <result column="productDesc" property="productDesc"/>
            <result column="productStatus" property="productStatus"/>
        </association>

        <!--查詢映射會員信息-->
        <association property="member" javaType="domain.Member">
            <id column="mid" property="id"/>
            <result column="name" property="name"/>
            <result column="nickname" property="nickname"/>
            <result column="phoneNum" property="phoneNum"/>
            <result column="email" property="email"/>
        </association>

        <!--根據中間表查詢旅客信息-->
        <!-- 關聯旅客明細信息
           一個訂單關聯查詢出了多條旅客,要使用collection映射
           collection:對關聯查詢到的多條記錄映射到集合中
           property:將關聯查詢到的多條記錄映射到orders類的那個屬性
           ofType:指定映射的集合屬性中pojo的類型
       -->
        <collection property="travellers"  ofType="domain.Traveller">
            <id column="tid" property="id"/>
            <result column="name" property="name"/>
            <result column="sex" property="sex"/>
            <result column="phoneNum" property="phoneNum"/>
            <result column="credentialsType" property="credentialsType"/>
            <result column="credentialsNum" property="credentialsNum"/>
            <result column="travellerType" property="travellerType"/>
        </collection>
    </resultMap>

    <!--定義Order的ResultMap懶加載模式映射,嵌套查詢-->
    <resultMap id="OrderMapLazy" type="domain.Orders">
        <id property="id" column="id"/>
        <result property="orderNum" column="orderNum"/>
        <result property="orderTime" column="orderTime"/>
        <result property="orderStatus" column="orderStatus"/>
        <result property="peopleCount" column="peopleCount"/>
        <result property="payType" column="payType"/>
        <result property="orderDesc" column="orderDesc"/>
        <!--配置Order對象中product映射 ofType是類型,用全限定名或別名-->
        <!--一對一查詢-->
        <association property="product" javaType="domain.Product" select="dao.IProductDao.findById" column="productId" fetchType="lazy"/>
        <association property="member" javaType="domain.Member" select="dao.IMemberDao.findMemberById" column="memberId" fetchType="lazy"/>
        <!--多對多查詢,需要根據中間表來查詢-->
        <collection property="travellers" ofType="domain.Traveller" column="id" select="dao.ITraveller.findTravellerByOrderId" fetchType="lazy"/>
        <!--如果是一對多查詢,還是用colleaction標簽,只不過不需要通過中間表查詢-->
    </resultMap>

    <select id="findAll" resultMap="orderMap">
     select o.id as oid,o.memberid,o.orderDesc,o.orderNum,o.orderStatus,o.orderTime,o.payType,o.peopleCount,o.productId,
     p.id as pid,p.cityName,p.departureTime,p.productDesc,p.productName,p.productNum,p.productPrice,p.productStatus,
     t.id as tid,t.credentialsNum,t.credentialsType,t.`name`,t.phoneNum,t.sex,t.travellerType,
     m.id as mid,m.email,m.`name`,m.nickName,m.phoneNum
     from orders o LEFT OUTER JOIN order_traveller ot on o.id=ot.orderId , product p,traveller t,member m
     WHERE o.productId = p.id and t.id = ot.travellerId and m.id = o.memberid
    </select>

    <select id="findAll1" resultMap="OrderMapLazy">
        select * from orders
    </select>

    <select id="getAll" resultType="domain.Orders">
        select * from orders
    </select>

    <select id="findById" resultMap="OrderMapLazy" parameterType="java.lang.String">
        select * from orders where id = #{id}
    </select>

</mapper>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM