Mybatis表关联一对多、多对一、多对多

 项目工程结构如下:

1. 搭建MyBatis框架环境

首先需要引入两个包:mybatis.jar 和 sqljdbc42.jar包

若分页需要导入两个包:pagehelper-5.1.0.jar 和  jsqlparser-1.0.jar

设置 mybatis 配置文件:SqlMapConfig.xml, 在 src目录下建立此文件,内容如下:

<?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">

<!-- 注意 <plugins> 在xml文件中的位置,必须要符合 http://mybatis.org/dtd/mybatis-3-config.dtd 中指定的顺序:-->
<!-- configuration (properties?, settings?, typeAliases?, typeHandlers?, 
    objectFactory?, objectWrapperFactory?, plugins?, environments?, databaseIdProvider?, mappers?) -->
<configuration>     
    <!-- 为SQL定义部分的parameterType或resultType属性指定自定义类型的别名 -->
    <typeAliases>              
        <typeAlias alias="ServiceStation" type="com.mybatis.models.ServiceStation" />
        <typeAlias alias="InspectorInfo" type="com.mybatis.models.InspectorInfo" />
        <typeAlias alias="StationInspector" type="com.mybatis.models.StationInspector" />    
    </typeAliases>
    <!-- 配置分页拦截器 -->
    <plugins>    
        <!-- 配置分页插件  -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
        <!-- com.mybatis.util为PageHelper类所在包名 -->    
        <!-- <plugin interceptor="com.mybatis.util.PagePlugin"> -->
            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->        
            <!-- <property name="dialect" value="SQLite" /> -->
            <!-- <property name="pageSqlId" value=".*Page.*" /> -->
        <!-- </plugin> -->
    </plugins>   
    <!-- 设置数据库连接参数 -->
    <!-- 与spring 集成之后,这些可以完全删除,数据库连接的管理交给 spring 去管理 -->
    <environments default="development">
        <environment id="development">
        <transactionManager type="JDBC" />
            <dataSource type="POOLED">  
                <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
                <property name="url" value="jdbc:sqlserver://mssql-rw-cyp-coopbusiness.vip.test.suixinhuan.com;DatabaseName=CYP_CoopBusiness" />
                <property name="username" value="Umanager" />
                <property name="password" value="ASD123asd!1" />
           </dataSource>
        </environment>
    </environments>    
    <!-- 加载SQL定义文件 -->
    <!-- 这里交给sqlSessionFactory 的 mapperLocations属性去得到所有配置信息 -->
    <mappers>                   
         <mapper resource="com/mybatis/sql/ServiceStation.xml" />
         <mapper resource="com/mybatis/sql/InspectorInfo.xml" />
         <mapper resource="com/mybatis/sql/StationInspector.xml" />
    </mappers>
</configuration>
View Code

2. 编写实体类

首先创建一个包:com.mybatis.models,并在其下创建与数据库表对应的三个实体类,分别如下:

ServiceStation.java 类

package com.mybatis.models;

import java.util.Date;
import java.util.List;

/**
 * @author 自定义类
 * 服务站类
 */
public class ServiceStation {
    private String ID; 
    private String StationName; 
    private String CityCode; 
    private String CityName; 
    private String StationAddr; 
    private int IsEnabled; 
    private String Createor; 
    private String CreateorUser; 
    private Date CreateDate; 
    private List<StationInspector> StationInspectorList;
    private List<InspectorInfo> InspectorInfoList;
    
    public String toString() {
        return "服务站 [ ID = " + ID  + ", StationName = " + StationName + ", "
                + "CityCode = " + CityCode + ", CityName = " + CityName + "]\n";
    }
    public String getID() { 
        return ID; 
    } 
    public void setID(String ID) { 
        this.ID = ID; 
    } 
    public String getStationName() { 
        return StationName; 
    } 
    public void setStationName(String StationName) { 
        this.StationName = StationName; 
    } 
    public String getCityCode() { 
        return CityCode; 
    } 
    public void setCityCode(String CityCode) { 
        this.CityCode = CityCode; 
    }   
    public String getCityName() { 
        return CityName; 
    } 
    public void setCityName(String CityName) { 
        this.CityName = CityName; 
    } 
    public String getStationAddr() { 
        return StationAddr; 
    } 
    public void setStationAddr(String StationAddr) { 
        this.StationAddr = StationAddr; 
    } 
    public int getIsEnabled() { 
        return IsEnabled; 
    } 
    public void setIsEnabled(int IsEnabled) { 
       this.IsEnabled = IsEnabled; 
    } 
    public String getCreateor() { 
        return Createor; 
    } 
    public void setCreateor(String Createor) { 
        this.Createor = Createor; 
    } 
    public String getCreateorUser() { 
        return CreateorUser; 
    } 
    public void setCreateorUser(String CreateorUser) { 
        this.CreateorUser = CreateorUser; 
    } 
    public Date getCreateDate() { 
        return CreateDate; 
    } 
    public void setCreateDate(Date CreateDate) { 
        this.CreateDate = CreateDate; 
    }    
    public List<StationInspector> getStationInspectorList() {
        return StationInspectorList;
    }
    public void setStationInspectorList(List<StationInspector> StationInspectorList) {
        this.StationInspectorList = StationInspectorList;
    }
    public List<InspectorInfo> getInspectorInfoList() {
        return InspectorInfoList;
    }
    public void setInspectorInfoList(List<InspectorInfo> InspectorInfoList) {
        this.InspectorInfoList = InspectorInfoList;
    }
}
View Code

InspectorInfo.java 类 

package com.mybatis.models;

import java.util.Date;
import java.util.List;

/**
 * @author 自定义类
 * 评估师类
 */
public class InspectorInfo {
    private String ID; 
    private String CityCode; 
    private int InspectorID; 
    private String InspectorName; 
    private String InspectorUser; 
    private String Createor; 
    private String CreateorUser; 
    private Date CreateDate; 
    private List<ServiceStation> ServiceStationList;
    
    public String toString() {
        return "评估师 [ CityCode = " + CityCode  + ", InspectorID = " + InspectorID + ", "
                + "InspectorName = " + InspectorName + ", InspectorUser = " + InspectorUser + "]\n";
    }
    public String getID() { 
        return ID; 
    } 
    public void setID(String ID) { 
        this.ID = ID; 
    } 
    public String getCityCode() { 
        return CityCode; 
    } 
    public void setCityCode(String CityCode) { 
        this.CityCode = CityCode; 
    } 
    public int getInspectorID() { 
        return InspectorID; 
    } 
    public void setInspectorID(int InspectorID) { 
        this.InspectorID = InspectorID; 
    }   
    public String getInspectorName() { 
        return InspectorName; 
    } 
    public void setInspectorName(String InspectorName) { 
        this.InspectorName = InspectorName; 
    } 
    public String getInspectorUser() { 
        return InspectorUser; 
    } 
    public void setInspectorUser(String InspectorUser) { 
        this.InspectorUser = InspectorUser; 
    }    
    public String getCreateor() { 
        return Createor; 
    } 
    public void setCreateor(String Createor) { 
        this.Createor = Createor; 
    } 
    public String getCreateorUser() { 
        return CreateorUser; 
    } 
    public void setCreateorUser(String CreateorUser) { 
        this.CreateorUser = CreateorUser; 
    } 
    public Date getCreateDate() { 
        return CreateDate; 
    } 
    public void setCreateDate(Date CreateDate) { 
        this.CreateDate = CreateDate; 
    }      
    public List<ServiceStation> getServiceStationList() {
        return ServiceStationList;
    }
    public void setServiceStationList(List<ServiceStation> ServiceStationList) {
        this.ServiceStationList = ServiceStationList;
    }
}
View Code

StationInspector.java 类

package com.mybatis.models;

import java.util.Date;

/**
 * @author 自定义类
 * 服务站与评估师关系类
 */
public class StationInspector {
    private String ID; 
    private String StationID; 
    private int InspectorID; 
    private String Inspector; 
    private String InspectorUser; 
    private int InspectorRole; 
    private Date DateRule;
    private String Createor; 
    private String CreateorUser; 
    private Date CreateDate; 
    private ServiceStation ServiceStation;
    
    public String toString() {
        return "评估师 [ StationID = " + StationID  + ", InspectorID = " + InspectorID + ", "
                + "Inspector = " + Inspector + ", InspectorUser = " + InspectorUser + "]\n";
    }
    public String getID() { 
        return ID; 
    } 
    public void setID(String ID) { 
        this.ID = ID; 
    } 
    public String getStationID() { 
        return StationID; 
    } 
    public void setStationID(String StationID) { 
        this.StationID = StationID; 
    } 
    public int getInspectorID() { 
        return InspectorID; 
    } 
    public void setInspectorID(int InspectorID) { 
        this.InspectorID = InspectorID; 
    }   
    public String getInspector() { 
        return Inspector; 
    } 
    public void setInspector(String Inspector) { 
        this.Inspector = Inspector; 
    } 
    public String getInspectorUser() { 
        return InspectorUser; 
    } 
    public void setInspectorUser(String InspectorUser) { 
        this.InspectorUser = InspectorUser; 
    } 
    public int getInspectorRole() { 
        return InspectorRole; 
    } 
    public void setInspectorRole(int InspectorRole) { 
       this.InspectorRole = InspectorRole; 
    } 
    public Date getDateRule() { 
        return DateRule; 
    } 
    public void setDateRule(Date DateRule) { 
        this.DateRule = DateRule; 
    }    
    public String getCreateor() { 
        return Createor; 
    } 
    public void setCreateor(String Createor) { 
        this.Createor = Createor; 
    } 
    public String getCreateorUser() { 
        return CreateorUser; 
    } 
    public void setCreateorUser(String CreateorUser) { 
        this.CreateorUser = CreateorUser; 
    } 
    public Date getCreateDate() { 
        return CreateDate; 
    } 
    public void setCreateDate(Date CreateDate) { 
        this.CreateDate = CreateDate; 
    }   
    public ServiceStation getServiceStation() { 
        return ServiceStation; 
    } 
    public void setServiceStation(ServiceStation ServiceStation) { 
        this.ServiceStation = ServiceStation; 
    } 
}
View Code

3. 编写SQL定义文件(映射文件)

首先创建一个包:com.mybatis.sql,并在其下创建与这三个实体类对应的映射文,详细如下代码所示:

ServiceStation.java 类对应的映射文件 ServiceStation.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">

<!-- namespace指定和哪个接口映射 -->
<mapper namespace="com.mybatis.dao.ServiceStationMapper">
    <!-- resultType是select特有 -->
    <select id="findAll" resultType="com.mybatis.models.ServiceStation">
        select * from T_TRA_ServiceStation
    </select>
    
    <select id="findAllPage" resultType="ServiceStation" parameterType="String">
        select * from T_TRA_ServiceStation where CityCode=#{CityCode}
    </select>
     
    <select id="findById" resultType="ServiceStation" parameterType="String">
        select * from T_TRA_ServiceStation where ID=#{ID}
    </select>
    
    <insert id="save" parameterType="ServiceStation">
        insert into T_TRA_ServiceStation values (#{ID},#{StationName},#{CityCode},#{CityName})
    </insert>

    <update id="update" parameterType="com.mybatis.models.ServiceStation">
        update T_TRA_ServiceStation set Createor=#{Createor},CreateorUser=#{CreateorUser} where ID=#{ID}
    </update>

    <!-- 如果parameterType为单个值,#{标识符}表达式标识符没有约定 -->
    <delete id="delete" parameterType="String">
        delete from T_TRA_ServiceStation where ID=#{ID}
    </delete>           
    
    <!-- Mybatis表关联多对多查询 方法配置  -->                  
    <resultMap type="ServiceStation" id="resultServiceStationMap">
        <result property="StationName" column="StationName" />
        <result property="CityCode" column="CityCode" />
        <result property="CityName" column="CityName" />
        <collection property="InspectorInfoList"           
             select="com.mybatis.dao.StationInspectorMapper.getInspectorInfoListByStationID"
             column="ID" />
    </resultMap>
    <select id="selectServiceStation" resultMap="resultServiceStationMap" parameterType="String">
        select * from T_TRA_ServiceStation where DeleteTag = 0 AND CityCode='110100' AND ID=#{ID}
    </select>
       
</mapper>
View Code

InspectorInfo.java 类对应的映射文件 InspectorInfo.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">

<!-- namespace指定和哪个接口映射 -->
<mapper namespace="com.mybatis.dao.InspectorInfoMapper">
    <!-- resultType是select特有 -->
    <select id="findAll" resultType="com.mybatis.models.InspectorInfo">
        select * from T_TRA_InspectorInfo
    </select>      
     
    <select id="findById" resultType="InspectorInfo" parameterType="String">
        select * from T_TRA_InspectorInfo where ID=#{ID}
    </select>
    
    <parameterMap type="com.mybatis.models.InspectorInfo" id="parameterInspectorInfoMap">
        <parameter property="ID"/>
        <parameter property="CityCode"/>
        <parameter property="InspectorID"/>
        <parameter property="InspectorName"/>
    </parameterMap>    
    <insert id="save" parameterMap="parameterInspectorInfoMap">
        insert into T_TRA_InspectorInfo values (#{ID},#{CityCode},#{InspectorID},#{InspectorName})
    </insert>
  
    <!-- Mybatis表关联多对多查询 方法配置  -->      
    <resultMap type="InspectorInfo" id="resultInspectorInfoMap">
        <result property="CityCode" column="CityCode" />
        <result property="InspectorID" column="InspectorID" />
        <collection property="ServiceStationList"           
             select="com.mybatis.dao.StationInspectorMapper.getServiceStationListByInspectorID"
             column="InspectorID" />
    </resultMap>
    <select id="selectInspectorInfo" resultMap="resultInspectorInfoMap"    parameterType="int">
        select * from T_TRA_InspectorInfo WHERE DeleteTag = 0 AND CityCode = '110100' AND InspectorID=#{InspectorID}
    </select>  
              
</mapper>
View Code

StationInspector.java 类对应的映射文件 StationInspector.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">

<!-- namespace指定和哪个接口映射 -->
<mapper namespace="com.mybatis.dao.StationInspectorMapper">  
    <!-- Mybatis表关联一对多查询 方法配置  -->    
    <resultMap type="ServiceStation" id="resultServiceStationMap">
        <id property="ID" column="ID" />
        <result property="ID" column="ServiceStation_ID" /> <!-- 注意这列起了别名 -->
        <result property="StationName" column="StationName" />
        <result property="CityCode" column="CityCode" />
        <result property="CityName" column="CityName" />
        <!-- 方法1 多表链接查询方式 -->
        <!-- <collection property="StationInspectorList" ofType="com.mybatis.models.StationInspector">         
            <id property="ID" column="ID" javaType="string" jdbcType="VARCHAR" /> 
            <result property="StationID" column="StationID" />   
            <result property="InspectorID" column="InspectorID" javaType="int" jdbcType="INTEGER" /> 
            <result property="Inspector" column="Inspector" javaType="string" jdbcType="VARCHAR" />
            <result property="InspectorUser" column="InspectorUser" /> 
            <result property="InspectorRole" column="InspectorRole" /> 
        </collection> -->
        <!-- 方法2 多表单独查询方式 -->
        <collection property="StationInspectorList" ofType="com.mybatis.models.StationInspector"
                    select="findStationInspector"
                    column="ID" />        
    </resultMap>
    
    <!-- 注意:两张表中的主键id字段名要唯一,例如不能都写id,不然的话,在一对多查询的时候就会出现只有一条记录 -->
    <!-- <select id="selectServiceStation" resultMap="resultServiceStationMap" parameterType="String">
        SELECT SS.ID AS ServiceStation_ID,SS.StationName,SS.CityCode,SS.CityName,SI.StationID,SI.InspectorID,SI.Inspector,SI.InspectorUser,SI.InspectorRole
        FROM T_TRA_ServiceStation AS SS WITH (NOLOCK) 
        LEFT JOIN T_TRA_StationInspector AS SI WITH (NOLOCK) ON SS.ID=SI.StationID AND SI.DeleteTag=0 AND SI.DateRule='2018-08-01'
        WHERE SS.CityCode='110100' AND SS.ID=#{ID}
        ORDER BY SI.InspectorID    
    </select> -->   
    
    <!-- 方法2 多表单独查询方式 -->
    <select id="findStationInspector" resultType="com.mybatis.models.StationInspector">
        select * from T_TRA_StationInspector where StationID=#{ID} AND DeleteTag=0 AND DateRule='2018-08-01'
    </select>    
    <select id="selectServiceStation2" resultMap="resultServiceStationMap">
        select * from T_TRA_ServiceStation where CityCode='110100' AND ID=#{ID}
    </select>
       
    <!-- Mybatis表关联多对一查询 方法配置  -->    
    <resultMap type="com.mybatis.models.StationInspector" id="resultStationInspectorMap">
        <id property="ID" column="ID" />
        <result property="StationID" column="StationID" />   
        <result property="InspectorID" column="InspectorID" /> 
        <result property="Inspector" column="Inspector" />
        <result property="InspectorUser" column="InspectorUser" /> 
        <result property="InspectorRole" column="InspectorRole" />     
        <!-- 方法1 多表链接查询方式 -->
        <!-- <association property="ServiceStation" javaType="com.mybatis.models.ServiceStation">         
            <id property="ID" column="ID" />
            <result property="ID" column="ServiceStation_ID" /> 
            <result property="StationName" column="StationName" />
            <result property="CityCode" column="CityCode" />
            <result property="CityName" column="CityName" />
        </association> -->   
        <!-- 方法2 多表单独查询方式 -->
        <association property="ServiceStation" javaType="com.mybatis.models.ServiceStation"
             select="findServiceStation"
             column="StationID" />
    </resultMap>
        
    <!-- 注意:两张表中的主键id字段名要唯一,例如不能都写id,不然的话,在一对多查询的时候就会出现只有一条记录 -->
    <!-- <select id="selectStationInspector" resultMap="resultStationInspectorMap" parameterType="int">
        SELECT SS.ID AS ServiceStation_ID,SS.StationName,SS.CityCode,SS.CityName,SI.StationID,SI.InspectorID,SI.Inspector,SI.InspectorUser,SI.InspectorRole
        FROM T_TRA_StationInspector AS SI WITH (NOLOCK) 
        INNER JOIN T_TRA_ServiceStation AS SS WITH (NOLOCK) ON SS.ID=SI.StationID AND SS.CityCode='110100'
        WHERE SI.DeleteTag=0 AND SI.DateRule='2018-08-01' AND SI.InspectorID=#{InspectorID}      
        ORDER BY SI.InspectorID    
    </select> -->      
    
    <!-- 方法2 多表单独查询方式 -->
    <select id="findServiceStation" resultType="com.mybatis.models.ServiceStation">
        select * from T_TRA_ServiceStation where ID=#{ID} AND CityCode='110100'
    </select>    
    <select id="selectStationInspector2" resultMap="resultStationInspectorMap">
        select * from T_TRA_StationInspector where DeleteTag=0 AND DateRule='2018-08-01' AND InspectorID = #{InspectorID}  
    </select>
          
    <!-- Mybatis表关联多对多查询 方法配置  -->     
    <!-- 根据一个服务站ID,查看这个服务站下的所有的评估师 -->
    <resultMap type="InspectorInfo" id="resultInspectorInfoMap_2">
        <result property="CityCode" column="CityCode" />
        <result property="InspectorID" column="InspectorID" />
        <result property="InspectorName" column="InspectorName" />
    </resultMap>
    
    <select id="getInspectorInfoListByStationID" resultMap="resultInspectorInfoMap_2" parameterType="String">
        SELECT II.*, SI.StationID
        FROM T_TRA_InspectorInfo II, T_TRA_StationInspector SI
        WHERE II.InspectorID=SI.InspectorID AND SI.StationID=#{ID} AND SI.DeleteTag=0 AND SI.DateRule='2018-08-01'
    </select>
    
    <!-- 根据一个评估师ID,查看这个评估师所对应的所有服务站-->
    <resultMap type="ServiceStation" id="resultServiceStationMap_2">
        <result property="StationName" column="StationName" />
        <result property="CityCode" column="CityCode" />
        <result property="CityName" column="CityName" />
    </resultMap> 
    
    <select id="getServiceStationListByInspectorID" resultMap="resultServiceStationMap_2" parameterType="int">
        SELECT SS.*, SI.InspectorID
        FROM T_TRA_ServiceStation SS, T_TRA_StationInspector SI
        WHERE SS.ID=SI.StationID AND SI.InspectorID=#{InspectorID} AND SI.DeleteTag=0 AND SI.DateRule in ('2018-06-01','2018-08-01','2018-09-01')
    </select>
</mapper>
View Code

说明:SQL参数部分,可以使用${标识符}或#{标识符},如果使用#{}内部采用预编译机制执行SQL操作。如果使用${}内部采用非预编译过程。

下面是对这几个配置文件一点解释说明:

1、配置文件 SqlMapConfig.xml 是 mybatis 用来建立 sessionFactory,里面主要包含了数据库连接相关内容,还有 java 类所对应的别名,比如:<typeAlias alias="ServiceStation" type="com.mybatis.models.ServiceStation" /> 这个别名非常重要,在具体的类的映射中,比如:ServiceStation.xml 中 resultType 或 parameterType 就是对应这个。要保持一致,这里的 resultType 还有另外单独的定义方式,后面学习到我们再详细介绍说明。

2、SqlMapConfig.xml 里面 的  <mapper resource="com/mybatis/sql/ServiceStation.xml" /> 是包含要映射的类的 xml 配置文件。

3、在ServiceStation.xml 文件里面主要是定义各种 SQL 语句,以及这些语句的参数,以及要返回的类型等等。

4. 编写Mapper接口(Mapper映射器)

首先创建一个包:com.mybatis.dao,并在其下创建三个接口,分别如下:

ServiceStationMapper.java 类:

package com.mybatis.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.mybatis.models.ServiceStation;
import com.mybatis.util.Page;

/**
 * 编写Mapper接口(Mapper映射器)
 * 方法定义参考SQL定义的id、parameterType、resultType属性
 * 1.方法名与id属性一致
 * 2.参数类型与parameterType属性一致
 * 3.返回结果:多行查询List<resultType>;单行查询 resultType;增删改为void或int
 * 4.SQL定义文件中namespace="com.mybatis.dao.ServiceStationMapper"
 */
public interface ServiceStationMapper {
      public List<ServiceStation> findAll();
	  
      public List<ServiceStation> findAllPage(@Param("CityCode") String CityCode);
	  
      public List<ServiceStation> findAllPage(@Param("page") Page page, @Param("CityCode") String CityCode);

      public ServiceStation findById(String id);

      public int save(ServiceStation obj);

      public int update(ServiceStation obj);

      public int delete(String id);  
      
      /*
       * 给多对多查询用
       */
      public ServiceStation selectServiceStation(String StationID);
}

InspectorInfoMapper.java 类:

package com.mybatis.dao;

import com.mybatis.models.InspectorInfo;

/**
 * 编写Mapper接口(Mapper映射器)
 * 方法定义参考SQL定义的id、parameterType、resultType属性
 * 1.方法名与id属性一致
 * 2.参数类型与parameterType属性一致
 * 3.返回结果:多行查询List<resultType>;单行查询 resultType;增删改为void或int
 * 4.SQL定义文件中namespace="com.mybatis.dao.InspectorInfoMapper"
 */
public interface InspectorInfoMapper {	
      /*
       * 给多对多查询用
       */
      public InspectorInfo selectInspectorInfo(int InspectorID);    
}

StationInspectorMapper.java 类:

package com.mybatis.dao;

import com.mybatis.models.ServiceStation;
import com.mybatis.models.StationInspector;

/**
 * 编写Mapper接口(Mapper映射器)
 * 方法定义参考SQL定义的id、parameterType、resultType属性
 * 1.方法名与id属性一致
 * 2.参数类型与parameterType属性一致
 * 3.返回结果:多行查询List<resultType>;单行查询 resultType;增删改为void或int
 * 4.SQL定义文件中namespace="com.mybatis.dao.StationInspectorMapper"
 */
public interface StationInspectorMapper {
      /*
       * 给一对多查询用
       */
      public ServiceStation selectServiceStation(String StationID);
      
      /*
       * 给一对多查询用
       */
      public ServiceStation selectServiceStation2(String StationID);
      
      /*
       * 给多对一查询用
       */
      public StationInspector selectStationInspector(int InspectorID);
      
      /*
       * 给多对一查询用
       */
      public StationInspector selectStationInspector2(int InspectorID);
}

5. 获取SqlSession操作

package com.mybatis.dao;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/*
 * 获取SqlSession操作(公共方法)
 */
public class MyBatisUtil {
    public static SqlSession getSession() {  
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        Reader reader;
        try {
            reader = Resources.getResourceAsReader("SqlMapConfig.xml");
            SqlSessionFactory factory = builder.build(reader);   
            SqlSession session = factory.openSession();
            return session;
        } catch (IOException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
            return null;
        }      
    }
}
View Code

6. 利用SqlSession获取Mapper接口对象

运行程序测试结果,在 src 目录下建立一个包:com.mybatis,并在其下创建一个类:HelloMyBatisProgram, 来运行测试配置环境是否成功,具体代码如下示:

package com.mybatis;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatis.dao.InspectorInfoMapper;
import com.mybatis.dao.MyBatisUtil;
import com.mybatis.dao.ServiceStationMapper;
import com.mybatis.dao.StationInspectorMapper;
import com.mybatis.models.ServiceStation;
import com.mybatis.models.InspectorInfo;
import com.mybatis.models.StationInspector;
//import com.mybatis.util.Page;

/*
 * 测试类
 */
public class HelloMyBatisProgram {
     public static void main(String[] args) {
          SqlSession session = MyBatisUtil.getSession();
          //由框架生成ServiceStationMapper接口实现对象
          ServiceStationMapper ssDaoMaper = session.getMapper(ServiceStationMapper.class);
          InspectorInfoMapper iiDaoMaper = session.getMapper(InspectorInfoMapper.class);
          StationInspectorMapper siDaoMaper = session.getMapper(StationInspectorMapper.class);
          //System.out.println(ssDaoMaper.getClass().getName());        
          System.out.println("===========分页获取所有服务站列表============");        
          //Page page = new Page();
           //page.setShowCount(3);
          //page.setCurrentPage(1);
          //List<ServiceStation> listPage = ssDaoMaper.findAllPage(page, "110100");    
          //System.out.println("分页查找总数:" + page.getTotalCount());
          
          //分页设置放在查询之前            
          Page<Object> page = PageHelper.startPage(1, 5, "StationName");
          List<ServiceStation> listPage = ssDaoMaper.findAllPage("110100");        
          for(ServiceStation item:listPage) {
              System.out.println(item.getStationName()+"  "+item.getCityCode()+"  "+item.getCityName());
          }     
          System.out.println("当前页码:"+page.getPageNum());
          System.out.println("每页的记录数:"+page.getPageSize());
          System.out.println("总记录数:"+page.getTotal());
          System.out.println("总页码:"+page.getPages());        
          System.out.println("===========获取所有服务站列表============");
          //分页设置放在查询之前            
          page = PageHelper.startPage(1, 3, "StationName desc");
          List<ServiceStation> list = ssDaoMaper.findAll(); 
          for(ServiceStation item:list) {
              System.out.println(item.getStationName()+"  "+item.getCityCode()+"  "+item.getCityName());
          }          
          PageInfo<ServiceStation> info = new PageInfo<ServiceStation>(list, 3);                    
          System.out.println("当前页码:"+info.getPageNum()); 
          System.out.println("每页的记录数:"+info.getPageSize());
          System.out.println("总记录数:"+info.getTotal());
          System.out.println("总页码:"+info.getPages());
          System.out.println("是否第一页:"+info.isIsFirstPage());
          System.out.println("连续显示的页码:");
          int[] nums = info.getNavigatepageNums();
          for (int i = 0; i < nums.length; i++) {
              System.out.println(nums[i]);
          }
          System.out.println("===========多表关联【一对多】查询 ============");        
          ServiceStation objServiceStation = siDaoMaper.selectServiceStation2("591559937214171136");       
          System.out.println(objServiceStation);         
          List<StationInspector> list1 = objServiceStation.getStationInspectorList();
          System.out.println(list1.size());
          System.out.println(list1);    
          System.out.println("===========多表关联【多对一】查询 ============");              
          StationInspector objStationInspector = siDaoMaper.selectStationInspector2(67884);    
          System.out.println(objStationInspector);    
          System.out.println(objStationInspector.getServiceStation());
          System.out.println("===========多表关联【多对多】查询 ============");    
          InspectorInfo objInspectorInfo = iiDaoMaper.selectInspectorInfo(67884);       
          System.out.println(objInspectorInfo);         
          List<ServiceStation> list2 = objInspectorInfo.getServiceStationList();
          System.out.println(list2.size());
          System.out.println(list2);    
          System.out.println("===========");       
          ServiceStation objServiceStation2 = ssDaoMaper.selectServiceStation("591559937214171136");       
          System.out.println(objServiceStation2);         
          List<InspectorInfo> list3 = objServiceStation2.getInspectorInfoList();
          System.out.println(list3.size());
          System.out.println(list3);    
          System.out.println("===========查找单个服务站信息============");        
          ServiceStation findObj = ssDaoMaper.findById("598212333755587533");  
          System.out.println(findObj.getStationName()+"  "+findObj.getCityCode()+"  "+findObj.getCityName());
          System.out.println("===========更新单个服务站信息============");        
          ServiceStation updateObj = ssDaoMaper.findById("598212333755587533");         
          updateObj.setCreateor("周锐北京");
          updateObj.setCreateorUser("zhouruibj");
          // 执行更新
          int result = ssDaoMaper.update(updateObj);  
          // 提交事务(注意:增删改之后必须执行提交)
          session.commit();
          System.out.println("更新返回结果:" + result);        
          session.close();     
     }     
}
View Code

运行测试后部分截图如下:

  

posted @ 2018-09-26 15:50  以德为先  阅读(393)  评论(0编辑  收藏  举报