【发布时间】:2020-01-17 17:11:08
【问题描述】:
在我目前在 Spring Boot 应用程序中与 DDD 的斗争中,我陷入了僵局。我知道我的域实体不应该与基础设施层(休眠实体所在的位置)有任何联系。当然,我的领域层依赖于 Hibernate 实体的数据来完成它的操作。
所以在我的应用层中,我的服务加载 Hibernate 实体并在域实体中传递它。
这是我的域实体的示例:
package com.transportifygame.core.domain.objects;
import com.transportifygame.core.domain.OperationResult;
import com.transportifygame.core.domain.constants.Garages;
import com.transportifygame.core.domain.exceptions.garages.NotAvailableSpotException;
import com.transportifygame.core.infrastructure.entities.CompanyEntity;
import com.transportifygame.core.infrastructure.entities.GarageEntity;
import com.transportifygame.core.infrastructure.entities.LocationEntity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@RequiredArgsConstructor
@AllArgsConstructor
public class Garage {
private GarageEntity garage;
public static Integer getAvailableSlots(Garages.Size size) {
switch (size) {
case SMALL:
return Garages.Slots.SMALL;
case MEDIUM:
return Garages.Slots.MEDIUM;
case LARGE:
return Garages.Slots.LARGE;
case HUGE:
return Garages.Slots.HUGE;
}
return 0;
}
public static Double getGaragePriceToBuy(Garages.Size size) {
switch (size) {
case SMALL:
return Garages.Prices.BUY_SMALL;
case MEDIUM:
return Garages.Prices.BUY_MEDIUM;
case LARGE:
return Garages.Prices.BUY_LARGE;
case HUGE:
return Garages.Prices.BUY_HUGE;
}
return 0.0;
}
public static OperationResult<GarageEntity, Object> buy(
Garages.Size size,
CompanyEntity company,
LocationEntity location
) {
// As we had changed the company object, we have to refresh
var newGarage = new GarageEntity();
newGarage.setCompany(company);
newGarage.setLocation(location);
newGarage.setSize(size.ordinal());
newGarage.setSlotsAvailable(Garage.getAvailableSlots(size));
return new OperationResult<>(newGarage, null);
}
public static void hasAvailableSpot(GarageEntity garage) throws NotAvailableSpotException {
if (garage.getSlotsAvailable() == 0) {
throw new NotAvailableSpotException();
}
}
public static OperationResult<GarageEntity, Object> addFreeSlot(GarageEntity garage) {
garage.setSlotsAvailable(garage.getSlotsAvailable() - 1);
return new OperationResult<>(garage, null);
}
public static OperationResult<GarageEntity, Object> removeFreeSlot(GarageEntity garage) {
garage.setSlotsAvailable(garage.getSlotsAvailable() + 1);
return new OperationResult<>(garage, null);
}
}
现在的问题是,这是为域实体提供所需数据的正确方法吗?如果没有,正确的方法是什么?
是否使用工厂来构建基于休眠实体的域实体?域实体应该镜像休眠实体属性?
我也看过有人用这种方式在Hibernate实体中添加域实体的逻辑,但我认为这不是正确的做法。
【问题讨论】:
标签: java spring hibernate domain-driven-design