【问题标题】:Creating JPA Entity from base class从基类创建 JPA 实体
【发布时间】:2020-10-02 13:41:33
【问题描述】:

我有一个通过队列进入我的应用程序的注册表列表,我有一个来自公共库的注册表类

public class Registry {

   private String rowId;
   private String code;
   private String status;
}

并且我想将此注册表实体保留在关系数据库表中(其中 rowId 是主键,我还需要添加一个序列 ID)。所以我创建了一个扩展 Registry 的 jpa 实体

@Entity
public class RegistryEntity extends Registry {
   @Id
   private String rowId;
   @GeneratedValue(strategy = GenerationType.SEQUENCE)
   private Integer sequenceId;
}

public interface RegistryRespository extends JpaRepository<RegistryEntity, String> {}

是否有一种优雅的方式(无需实例化每个 RegistryEntity)将 List&lt;Registry&gt; 转换为 List&lt;RegistryEntity&gt;,以便我可以执行以下操作

List<Registry> registries = getFromQueue();

registryRespository.saveAll(RegistryEntityList) 

【问题讨论】:

  • 您必须以一种或另一种方式遍历 List 并创建 RegistryEntity 对象。你知道你定义了 rowId 两次吗?我的建议是不要让 RegistryEntity 扩展 Registry,因为 RegistryEntity 是您内部持久层的一部分,而 Registry 是公共合同的一部分。我宁愿把这两个分开。
  • 有多种映射机制可用于 DTO 对象和实体之间的映射,但我建议使用mapstruct,这里使用起来很方便。看mapstruct.orgbaeldung.com/mapstruct
  • 你也可以使用ModelMapper

标签: java jpa


【解决方案1】:

Spring 提供 API BeanUtils.copyProperties(source, destinate, ignore props) 只需通过符合您标准的参考。并且您将按照预期的结果完成。

【讨论】:

  • 谢谢,我可能会使用 List 并创建 RegistryEntity 对象。由于@id 注释,我在RegistryEntity 中有rowId。将 jpa 注释添加到超类中定义的 jpa 实体中的字段的正确方法是什么
猜你喜欢
  • 2016-03-01
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 2011-02-15
  • 2013-08-30
  • 2012-12-29
相关资源
最近更新 更多