首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

EJB 設計模式(二):Value Object 封裝欄位傳輸

     編輯:Java 相關知識

模式一痛點

  • 每個欄位獨立 getter/setter → 遠端呼叫次數多、網路開銷大。
  • 多欄位更新需多次交易 → 資料一致性難保證。

引入 Value Object (Struct)

public class CompanyStruct implements Serializable {
    public Integer comId;      // PK
    public String comName;
    public String comDescription;
    public Timestamp mutationDate;
}

public class EmployeeStruct implements Serializable {
    public Integer empId;      // PK
    public Integer comId;      // FK
    public String empFirstName;
    public String empLastName;
    public Timestamp mutationDate;
}

Entity Bean 精簡介面

public class CompanyBean implements EntityBean {
    // 單一 create:傳入 Struct
    public Integer ejbCreate(CompanyStruct struct) throws CreateException {
        this.comId = struct.comId;
        this.comName = struct.comName;
        this.comDescription = struct.comDescription;
        this.mutationDate = struct.mutationDate;
        return null;
    }

    // 單一 getData:回傳 Struct
    public CompanyStruct getData() {
        CompanyStruct result = new CompanyStruct();
        result.comId = this.comId;
        result.comName = this.comName;
        result.comDescription = this.comDescription;
        result.mutationDate = this.mutationDate;
        return result;
    }

    // 單一 setData:更新所有非 PK 欄位
    public void setData(CompanyStruct struct) {
        this.comName = struct.comName;
        this.comDescription = struct.comDescription;
        this.mutationDate = struct.mutationDate;
    }
}

優化:ejbCreate 內呼叫 setData

public Integer ejbCreate(CompanyStruct struct) throws CreateException {
    this.comId = struct.comId; // PK 必須先設定
    setData(struct);           // 其餘欄位委派
    return null;
}

優點

  • 一次遠端呼叫傳輸所有欄位,減少 RMI 開銷。
  • 單一交易邊界確保多欄位原子性更新。
  • 智慧更新:容器(如 Borland AppServer)僅寫入實際異動欄位。

殘留問題

  • Bean 與 Struct 仍有重複欄位宣告(模式三解決)。
  • 未處理 Bean 間關聯(模式五)。

現代對應:DTO + JPA

@Entity
public class Company {
    @Id Integer comId;
    String comName;
    String comDescription;
    Timestamp mutationDate;
}

public class CompanyDTO { // 非實體,單純資料傳輸
    Integer comId;
    String comName;
    String comDescription;
    Timestamp mutationDate;
}

// Service 層
@Transactional
public CompanyDTO create(CompanyDTO dto) {
    Company entity = mapper.toEntity(dto);
    entity = repo.save(entity);
    return mapper.toDto(entity);
}

結語

模式二確立「Value Object 封裝多欄位、單一方法傳輸」核心思想,解決分散式細粒度介面的效能與一致性問題。此模式演變為現代 DTO (Data Transfer Object) 模式,廣泛應用於微服務、REST API、GraphQL 等架構中。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved