Java 转换器是否应该直接访问存储库?
我在任何地方都找不到这个特定问题的答案,这让我对我的架构进行了二次猜测。基本上我有两个实体,BaseCategoryEntity和ItemEntityJava 转换器是否应该直接访问存储库?,java,spring-boot,spring-data-jpa,Java,Spring Boot,Spring Data Jpa,我在任何地方都找不到这个特定问题的答案,这让我对我的架构进行了二次猜测。基本上我有两个实体,BaseCategoryEntity和ItemEntity @Entity public class ItemEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID", unique = true, nullable = false) private Long itemId; @ManyToOne
@Entity
public class ItemEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", unique = true, nullable = false)
private Long itemId;
@ManyToOne
@JoinColumn(name = "BCID", nullable = false)
private BaseCategoryEntity baseCategory;
@Column(name = "NAME", unique = true, nullable = false)
private String name;
....
ItemEntity有它相应的DTO,Item
ItemController
接收项目
,将其传递给ItemService
,后者使用转换器将其保存到存储库
@Service
public class ItemService {
@Autowired
ItemRepository repository; //this is a CrudRepository
@Autowired
ItemConverter converter;
public void add(Item item){
repository.save(converter.convertFrom(item));
}
}
转换器是这样的
@Component
public class ItemConverter{
@Autowired
BaseCategoryConverter bcConverter;
public ItemEntity convertFrom(Item model) {
ItemEntity entity = new ItemEntity();
entity.setName(model.getName());
entity.setBaseCategory(bcConverter.convertFrom(model.getBaseCategoryName()));
return entity;
}
}
通过运行这段代码,我得到org.hibernate.TransientPropertyValueException:notnull属性引用了一个瞬时值错误,因为BaseCategoryEntity的id没有设置。
解决此问题的最简单方法似乎是将ItemRepository
自动连接到ItemConverter
和BaseCategoryRepository
到BaseCategoryConverter
,因此我可以将convertFrom
更改为首先检查实体是否已经存在并使用该实体,或者创建并保存它(如果没有)。
然而,转换器执行这种逻辑似乎不合适。根据您想要执行的操作,您可以简单地将
name
作为外键,而不是id
,然后它就可以工作了。我的意思是BCID
这应该是BCNAME
或类似的东西。在这个特殊的例子中,是的,但问题的目的是概念,因为我有多个像这2个实体,但有一堆其他字段。我选择这些来代表问题,因为它们是最简单的。如果你想保留现在的东西,那么你回答了你的问题。不是真的。我对Spring Boot相当陌生,因此我不知道所有的最佳实践。我想让ItemService
成为唯一一个访问存储库的人,但通过此设置,转换器也需要访问它。最佳做法是我将您的name
注释为外键
,而您忘记访问存储库或服务
。