myBatis实现三级嵌套复杂对象的赋值问题

平常我们工作中基本最多两级嵌套,但是有时候难免会遇到三级嵌套的业务场景,笔者最近就碰到了,使用一般的嵌套发现赋值为空,这可难倒了菜逼的我,后来在stackoverflow的帮助下终于搜到了解决办法,完美解决了问题 ,总结一下,方便有需要的同学,下面直接上栗子:

首先上实体类:三级嵌套如下 (电站 -----> 电桩 ---->电枪)

电站实体类 (实体为JPA写法,不影响mybatis的使用)

package com.weima.cecapp.entities;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.util.Collections;
import java.util.List;
import java.util.Set;
@NoArgsConstructor
@Data
@Entity
@Table(name = "station_info")
public class StationInfo {
  /**
   * Auto-generated primary key.
   */
  @Id
  @GeneratedValue(generator = "uuid")
  @GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
  @Column(unique = true, nullable = false, updatable = false)
  private String id;

  @Column(name = "station_id")
  private String stationId;

  @Column(name = "operator_id")
  private String operatorId;

  @Column(name = "equipment_owner_id")
  private String equipmentOwnerId;

  @Column
  private String stationName;

  @Column
  private String countryCode;

  @Column
  private String areaCode;

  @Column
  private String address;

  @Column
  private String stationTel;

  @Column
  private String serviceTel;

  @Column
  private Integer stationType;

  @Column
  private Integer stationStatus;

  @Column
  private Integer parkNums;

  @Column
  private Double stationLng;

  @Column
  private Double stationLat;

  @Column
  private String siteGuide;

  @Column
  private Integer construction;

  @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, orphanRemoval = true, mappedBy = "ownerStationInfo")
  private List<StationPicture> pictures;

  @Column
  private String matchCars;

  @Column
  private String parkInfo;

  @Column
  private String busineHours;

  @Column(name = "busine_hours_in_milliseconds")
  private Long busineHoursInMilliseconds;

  @Column
  private String electricityFee;

  @Column
  private String serviceFee;

  @Column
  private String parkFee;

  @Column
  private String payment;

  @Column
  private Integer supportOrder;

  @Column
  private String remark;

  @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, orphanRemoval = true, mappedBy = "ownerStationInfo")
  @BatchSize(size = 20)
  private List<EquipmentInfo> equipmentInfos;

}

电站图片实体

package com.weima.cecapp.entities;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;

@Data
@Entity
@EqualsAndHashCode(of = {"url"})
@ToString(exclude = {"ownerStationInfo"})
@Table(name = "station_picture")
public class StationPicture {
  /**
   * Auto-generated primary key.
   */
  @Id
  @GeneratedValue(generator = "uuid")
  @GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
  @Column(unique = true, nullable = false, insertable = true, updatable = false)
  private String id;

  @ManyToOne(fetch = FetchType.EAGER, optional = false)
  @JoinColumn(nullable = false, updatable = false)
  private StationInfo ownerStationInfo;

  @Column
  private String url;
}

电桩实体类

package com.weima.cecapp.entities;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;

@Data
@Entity
@EqualsAndHashCode(of = {"equipmentId"})
@ToString(exclude = {"ownerStationInfo"})
@Table(name = "equipment_info")
public class EquipmentInfo {
  /**
   * Auto-generated primary key.
   */
  @Id
  @GeneratedValue(generator = "uuid")
  @GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
  @Column(unique = true, nullable = false, updatable = false)
  private String id;

  @Column(name = "equipment_id")
  private String equipmentId;

  @ManyToOne(fetch = FetchType.EAGER, optional = false)
  @JoinColumn(nullable = false, updatable = false)
  private StationInfo ownerStationInfo;

  @Column(name = "manufacturer_id")
  private String manufacturerId;

  @Column
  private String manufacturerName;

  @Column
  private String equipmentModel;

  @Column
  private String productionDate;

  public String getProductionDate() {
    String format = null;
    if (this.productionDate != null) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      try {
        format = sdf.format(sdf.parse(this.productionDate));
      } catch (ParseException e) {
        e.printStackTrace();
      }
      return format;
    }
    return format;
  }

  @Column
  private String equipmentType;

  @OneToMany(fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "ownerEquipmentInfo", cascade = {CascadeType.PERSIST})
  @BatchSize(size = 20)
  private List<ConnectorInfo> connectorInfos;

  @Column
  private Double equipmentLng;

  @Column
  private Double equipmentLat;

  @Column
  private Double power;

  @Column
  private String equipmentName;

  @Column(name = "equipment_no")
  //cpo's custom equipmentId mostly for Evstation
  private String equipmentNo;
}

电枪实体类

package com.weima.cecapp.entities;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;

@Data
@Entity
@EqualsAndHashCode(of = {"connectorId"})
@ToString(exclude = {"ownerEquipmentInfo"})
@Table(name = "connector_info")
public class ConnectorInfo {
  /**
   * Auto-generated primary key.
   */
  @Id
  @GeneratedValue(generator = "uuid")
  @GenericGenerator(name = "uuid", strategy = "org.hibernate.id.UUIDGenerator")
  @Column(unique = true, nullable = false, updatable = false)
  private String id;

  @ManyToOne(fetch = FetchType.EAGER, optional = false)
  @JoinColumn(nullable = false, updatable = false)
  private EquipmentInfo ownerEquipmentInfo;

  @Column(name = "connector_id")
  private String connectorId;

  @Column
  private String connectorName;

  @Column
  private Integer connectorType;

  @Column
  private Integer voltageUpperLimits;

  @Column
  private Integer voltageLowerLimits;

  @Column
  private Integer current;

  @Column
  private Double power;

  @Column
  private String parkNo;

  @Column
  private Integer nationalStandard;

  @Column(name = "connector_no")
  //cpo's custom connectorId mostly for Evstation
  private String connectorNo;
}

mapper 文件的resultMap映射及Sql语句的书写,要特别注意映射关系

<?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="com.hubject.cecapp.mapper.StationInfoAnyueMapper">

  <resultMap id="templateListResp" type="com.hubject.cecapp.entities.EquipmentInfo">
    <!-- 充电桩信息-->
    <id column  ="id          " property="id"/>
    <result column="equipment_id     " property="equipmentId"/>
    <result column="equipment_lat     " property="manufacturerName"/>
    <result column="equipment_lng     " property="equipmentModel"/>
    <result column="equipment_model    " property="productionDate"/>
    <result column="equipment_name    " property="manufacturerId"/>
    <result column="equipment_type    " property="equipmentType"/>
    <result column="manufacturer_id    " property="equipmentLng"/>
    <result column="manufacturer_name   " property="equipmentLat"/>
    <result column="power         " property="power"/>
    <result column="production_date    " property="equipmentName"/>
    <result column="owner_station_info_id " property="equipmentNo"/>
      <!-- 充电枪 信息列表 -->
    <collection property="connectorInfos" columnPrefix="f_" ofType="com.hubject.cecapp.entities.ConnectorInfo">
      <id column="id" property="id"/>
      <result column="connector_id" property="connectorId"/>
      <result column="connector_name" property="connectorName"/>
      <result column="connector_type" property="connectorType"/>
      <result column="voltage_upper_limits" property="voltageUpperLimits"/>
      <result column="voltage_lower_limits" property="voltageLowerLimits"/>
      <result column="current" property="current"/>
      <result column="power" property="power"/>
      <result column="park_no" property="parkNo"/>
      <result column="national_standard" property="nationalStandard"/>
      <result column="connector_no" property="connectorNo"/>
    </collection>
  </resultMap>

  <!-- 通用查询映射结果 -->
  <resultMap id="Base3ResultMap" type="com.hubject.cecapp.entities.StationInfo">
    <result column="id" property="id"/>
    <result column="address" property="address"/>
    <result column="area_code" property="areaCode"/>
    <result column="busine_hours" property="busineHours"/>
    <result column="construction" property="construction"/>
    <result column="country_code" property="countryCode"/>
    <result column="electricity_fee" property="electricityFee"/>
    <result column="equipment_owner_id" property="equipmentOwnerId"/>
    <result column="station_id" property="stationId"/>
    <result column="operator_id" property="operatorId"/>
    <result column="station_name" property="stationName"/>
    <result column="station_tel" property="stationTel"/>
    <result column="service_tel" property="serviceTel"/>
    <result column="station_type" property="stationType"/>
    <result column="station_status" property="stationStatus"/>
    <result column="park_nums" property="parkNums"/>
    <result column="station_lng" property="stationLng"/>
    <result column="station_lat" property="stationLat"/>
    <result column="site_guide" property="siteGuide"/>
    <result column="match_cars" property="matchCars"/>
    <result column="park_info" property="parkInfo"/>
    <result column="busine_hoursIn_milliseconds" property="busineHoursInMilliseconds"/>
    <result column="service_fee" property="serviceFee"/>
    <result column="park_fee" property="parkFee"/>
    <result column="payment" property="payment"/>
    <result column="support_order" property="supportOrder"/>
    <result column="remark" property="remark"/>
    <result column="templateListResp" property="remark"/>
    <collection property="equipmentInfos" columnPrefix="t_" resultMap="templateListResp"/>
  </resultMap>

-- 要特别注意的是 t_f_ 的前缀,这个关乎到映射不映射上的根本。
<select id="queryAreaForAnyoCharging" resultMap="Base3ResultMap">
    select
       a.id                   as    id,
       a.station_id               as    station_id,
       a.operator_id              as    operator_id,
       a.equipment_owner_id           as    equipment_owner_id,
       a.station_name              as    station_name,
       a.country_code              as    country_code,
       a.area_code               as    area_code,
       a.address                as    address,
       a.station_tel              as    station_tel,
       a.service_tel              as    service_tel,
       a.station_type              as    station_type,
       a.station_status             as    station_status,
       a.park_nums               as    park_nums,
       a.station_lng              as    station_lng,
       a.station_lat              as    station_lat,
       a.site_guide               as    site_guide,
       a. construction             as    construction,
       a.match_cars               as    match_cars,
       a.park_info               as    park_info,
       a.busine_hours              as    busine_hours,
       a.busine_hours_in_milliseconds      as    busine_hours_in_milliseconds,
       a. electricity_fee            as    electricity_fee,
       a. service_fee              as    service_fee,
       a. park_fee               as    park_fee,
       a. payment                as    payment,
       a. support_order             as    support_order,
       a.remark                 as    remark
       ,
       e.id                   as    t_id               ,
       e.equipment_id              as    t_equipment_id          ,
       e.equipment_lat             as    t_equipment_lat         ,
       e.equipment_lng             as    t_equipment_lng         ,
       e.equipment_model            as    t_equipment_model        ,
       e.equipment_name             as    t_equipment_name         ,
       e.equipment_type             as    t_equipment_type         ,
       e.manufacturer_id            as    t_manufacturer_id        ,
       e.manufacturer_name           as    t_manufacturer_name       ,
       e.power                 as    t_power             ,
       e.production_date            as    t_production_date        ,
       e.owner_station_info_id         as    t_owner_station_info_id     ,
       e.equipment_no              as    t_equipment_no
       ,

       c.id                   as    t_f_id             ,
       c.power                 as    t_f_power           ,
       c.current                as    t_f_current          ,
       c.park_no                as    t_f_park_no          ,
       c.connector_id              as    t_f_connector_id        ,
       c.connector_name             as    t_f_connector_name       ,
       c.connector_type             as    t_f_connector_type       ,
       c.connector_no              as    t_f_connector_no        ,
       c.national_standard           as    t_f_national_standard     ,
       c.voltage_lower_limits          as    t_f_voltage_lower_limits    ,
       c.voltage_upper_limits          as    t_f_voltage_upper_limits    ,
       c.owner_equipment_info_id        as    t_f_owner_equipment_info_id

       from station_info a join equipment_info e on a.id = e.owner_station_info_id

         join connector_info c on e.id = c.owner_equipment_info_id

         where a.operator_id='MA59J8YL8'
  </select>

  </mapper>

希望为遇到同样需求的同学提供到帮助。

到此这篇关于myBatis实现三级嵌套复杂对象的赋值问题的文章就介绍到这了,更多相关myBatis三级嵌套复杂对象的赋值内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • MyBatis拦截器:给参数对象属性赋值的实例

    该拦截器的作用:在进行增加.修改等操作时,给数据模型的一些通用操作属性(如:创建人.创建时间.修改人.修改时间等)自动赋值. 该实现是在DAO层拦截,即存入DB前最后一层.后经分析,不是很合理,改为在service层拦截,用spring AOP来实现了,该代码遂弃用.不过已经测试可用,记录备忘. package com.development; import java.lang.reflect.InvocationTargetException; import java.util.Date; i

  • mybatis同一张表多次连接查询相同列赋值问题小结

    最近遇到的一些问题总结: 1. MySQL数据库同一张表做四次左连接查询数据冗余. a. mysql数据库连接查询 b. mysql表数据去重 2. mybatis查询相同列赋值重复问题. a. 使用mybatis强大的resultMap b. mysql数据查询别名 数据库表为 Create Table CREATE TABLE `STUDENT_SCORE` ( `score_id` int(11) unsigned NOT NULL AUTO_INCREMENT,//主键 `test_id

  • myBatis实现三级嵌套复杂对象的赋值问题

    平常我们工作中基本最多两级嵌套,但是有时候难免会遇到三级嵌套的业务场景,笔者最近就碰到了,使用一般的嵌套发现赋值为空,这可难倒了菜逼的我,后来在stackoverflow的帮助下终于搜到了解决办法,完美解决了问题 ,总结一下,方便有需要的同学,下面直接上栗子: 首先上实体类:三级嵌套如下 (电站 -----> 电桩 ---->电枪) 电站实体类 (实体为JPA写法,不影响mybatis的使用) package com.weima.cecapp.entities; import lombok.D

  • 解决Mybatis中foreach嵌套使用if标签对象取值的问题

    目录 foreach嵌套使用if标签对象取值问题 大体格式 解决办法 代码如下 Mybatis if 语句嵌套 要求 foreach嵌套使用if标签对象取值问题 最近做项目过程中,涉及到需要在 Mybatis 中 使用 foreach 进行循环读取传入的查询条件,动态拼接SQL语句,接口传入的查询条件格式:{"advanceSearchList":[{"searchType":10,"searchText":"12"}]} ,

  • Mybatis关联查询结果集对象嵌套的具体使用

    在查询时经常出现一对多”的关系,所有会出现嵌套对象的情况,Mybatis在resultMap提供了collection标签,本文适合有一定Mybatis基础的读者查阅 数据模型WeixinActivity2018User.java public class WeixinActivity2018User  implements Serializable{     /** serialVersionUID*/     private static final long serialVersionUI

  • MyBatis一对多嵌套查询的完整实例

    前言 嵌套查询的实现原理为两次查询,比如产品表为主表,图片表为从表通过product_id字段与产品表id字段关联实现一对多,嵌套查询 首先查询 主表的数据 然后将主表id字段赋值给从表实体类中product_id 字段(productId)然后通过dao接口路径映射找到对应的MyBatis XMl文件SQL语句ID如:com.liao.dao.DImgMapper.selectDImgByProductId 进行子查询也就是第二次查询.然后返回数据 数据库建表语句和测试数据如下: 数据库版本为

  • 解决mybatis 中collection嵌套collection引发的bug

    我就废话不多说了,大家还是直接看代码吧~ <resultMap id="ParentMap" type="org.example.mybatis.Parent"> <id column="Id" jdbcType="VARCHAR" property="id" /> <result column="Name" jdbcType="VARCHAR&q

  • 微信小程序 两种为对象属性赋值的方式详解

    微信小程序两种为对象属性赋值的方式 对应config.wxml <view> 阶段一<switch id="config1" checked bindchange="switchChange"/> </view> 对应config.js data:{ //定义对象 configs:{} } //方式一 switchChange:function(e){ //为对象的某一属性赋值 configs.config1={ }; conso

  • C++中对象的赋值与复制操作详细解析

    对象的赋值 如果对一个类定义了两个或多个对象,则这些同类的对象之间可以互相赋值,或者说,一个对象的值可以赋给另一个同类的对象.这里所指的对象的值是指对象中所有数据成员的值. 对象之间的赋值也是通过赋值运算符"="进行的.本来赋值运算符"="只能用来对单个的变量赋值,现在被扩展为两个同类对象之间的赋值,这是通过对赋值运算符的重载实现的. 实际上这个过程是通过成员复制来实现的,即将一个对象的成员值一一复制给另外一个对象的成员.对象赋值的一般形式: 对象名1=对象名2;

  • Mybatis多参数及实体对象传递实例讲解

    在使用Mybatis的时候,经常会有各种各样的参数传递,不同类型,不同个数的参数. 先上个例子: public List<LifetouchRelease> findOfficeList(@Param("lifetouchRelease") LifetouchRelease lifetouchRelease, @Param("advertisementId") String advertisementId, @Param("officeName

  • vue data对象重新赋值无效(未更改)的解决方式

    vue存在一个比较深的问题就是data中的属性对象如果在初始化的时候为{},那么后面在方法用普通的js语法赋值会无效 这里是data data() { return { model: {} }; } 这里是方法里的普通赋值 afterUpload(response) { this.model.icon = response.url; } 普通方法会无效,需要使用vue提供的方法重新显示声明 afterUpload(response) { this.$set(this.model,'icon',r

随机推荐