Search code examples
javaspring-boothexagonal-architecture

How to map domain object to Jpa entity using hexagonal architecture


after reading articles on hexagonal architecture, i decided to implement these practices. only i'm stuck in one place, i'd like to know how to map domain objects into domain entities. here is what i tried

//jpa entity

@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;
}

// domain model

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;
    }

// port out

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

// port in

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

// adapters out

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

}
// here I have an conversion error 


Solution

  • Here:

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

    You will have a conversion error because they're different classes as crush84 correctly pointed out. I think you need to go through the jpa Worker and create a new domain model Worker for each one.

    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
    }
    

    Be very careful about imports and usage of Worker - you don't want to mix them up. Maybe you could rename them to be something more descriptive to avoid confusion in the future? I hope this helps :D