如何使用六边形架构将域对象映射到 Jpa 实体

How to map domain object to Jpa entity using hexagonal architecture

在阅读了有关六边形建筑的文章后,我决定实施这些做法。只有我被困在一个地方,我想知道如何将域对象映射到域实体中。这是我试过的

//jpa实体

@Entity
@Data
public class Worker {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String phoneNumber;
    private String firstName;
    private String lastName;
    private String workerType;
    private String ifu;
    private String workerPicture;
    private String statut;
    
     @OneToMany(mappedBy = "worker")
      Set<CategoryWorker> category;
}

// 领域模型

public class Worker {
    private Long id;
    private String phoneNumber;
    private String firstName;
    private String lastName;
    private String workerType;
    private String ifu;
    private String imageParth;
    private String statut;
    }

//端口输出

public interface ListOfWorkerRepository {
    public List<Worker> findAll();
}

//端口在

public interface ListOfWorker {
    public List<Worker> findAll();
}

// 适配器输出

public class ListWorkerImpl implements ListOfWorkerRepository{
    WorkerJpaInterface workerJpaInterface;
    @Override
    
    public List<Worker> findAll() {
        
        return  workerJpaInterface.findAll();
    }

}
// here I have an conversion error 

我猜是因为两个 class 都叫 'Worker'。如果你将它重命名为 'WorkerJpa' 和 'WorkerDomain' 你就会发现问题所在。 我说 'I guess' 是因为我们没有看到有助于分析的堆栈跟踪和包结构。 您需要一种 WorkerMapper(例如实体到 Dto 映射器,java class 或使用 MapStruct 等)。通常它应该在 WorkerJpa 包中,因为我们假设外部 Worker class 结构可以改变并且应该由映射器调整到域实体。

这里:

public List<Worker> findAll() {
    return  workerJpaInterface.findAll();
}

您将遇到转换错误,因为它们与 crush84 正确指出的不同 类。我认为您需要通过 jpa Worker 并为每个模型创建一个新的域模型 Worker

public List<Worker> findAll() {
    List<Worker> jpaWorkers = workerJpaInterface.findAll(); 
    List<Worker> domWorkers = new ArrayList<>();
    // your IDE should scream at you here about different Worker classes
    // so you would have to specify explicitly which worker you're talking about
    for(Worker jpaWorker : jpaWorkers) {
        Worker domWorker = new Worker();
        domWorker.setPhoneNumber(jpaWorker.getPhoneNumber());
        domWorker.setName(jpaWorker.getName());
        //set all the properties of domain model worker 
        //using values from jpa worker
}

Worker 的导入和使用要非常小心 - 你不想混淆它们。也许您可以将它们重命名为更具描述性的名称以避免将来混淆?我希望这会有所帮助 :D