所以我有一个实体类“ RecipeClientConfig”,它与“ RecipeClientConfigParam”具有多对一的关系。
RecipeClientConfig:
@Entity
@Table(name="recipe_client_config", schema="app")
public class RecipeClientConfig {
@Id
@Column(name="recipe_client_config_id")
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "sequence-generator"
)
@SequenceGenerator(
name = "sequence-generator",
sequenceName = "app.recipe_client_config_seq",
allocationSize=1
)
private long recipeClientConfigId;
@Column(name="recipe_setup_id")
private int recipeSetupId;
@Column(name="personid", columnDefinition = "NVARCHAR(10)")
private String personId;
@Column(name="from_account_num")
private String fromAccountNum;
@Column(name="to_account_num")
private String toAccountNum;
@Column(name="status", columnDefinition = "CHAR(1)")
private String status;
@OneToMany(mappedBy="recipeClientConfig", cascade = CascadeType.ALL, fetch= FetchType.EAGER)
private List<RecipeClientConfigParam> configParams = new ArrayList<>();
RecipeClientConfigParam:
@Entity
@Table(name="recipe_client_config_params", schema="app")
public class RecipeClientConfigParam {
@Id
@Column(name="recipe_client_config_param_id")
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "sequence-generator"
)
@SequenceGenerator(
name = "sequence-generator",
sequenceName = "app.recipe_client_config_params_seq",
allocationSize=1
)
private long recipeClientConfigParamId;
@Column(name="param_name", columnDefinition = "NVARCHAR(50)")
private String paramName;
@Column(name="param_value", columnDefinition = "NVARCHAR(50)")
private String paramValue;
@ManyToOne
@JoinColumn(name = "recipe_client_config_id", nullable = false, updatable = false, insertable = true)
private RecipeClientConfig recipeClientConfig;
现在,该RecipeConfiguration能够由用户更新,在那里他们将向下传递DTO对象,然后映射到JPA实体。其中某些RecipeConfigParameters可能会或可能不会更新。
这是我的保存方法:
public void saveRecipeConfig (RecipeClientConfig recipeConfig) {
recipeConfig.setLastupdDat(LocalDateTime.now());
recipeConfig.setCreateDate(LocalDateTime.now());
List<RecipeClientConfigParam> params = recipeConfig.getConfigParams();
if (params != null) {
for (RecipeClientConfigParam param : params) {
param.setRecipeClientConfig(recipeConfig);
param.setCreateOp(recipeConfig.getPersonId());
param.setLastupdOp(recipeConfig.getPersonId());
param.setCreateDate(LocalDateTime.now());
param.setLastupdDat(LocalDateTime.now());
}
}
configRepository.saveAndFlush(recipeConfig);
}
如果仅保存更新的RecipeConfig实体对象,则将删除更新对象中不存在但数据库中存在的所有字段和RecipeConfigParameters。
为了简单起见,并非所有字段都在上面的代码中显示,并且某些字段和Parameter对象实际上甚至不应该被更新。
我真的想避免使用findById()或getOne()检索RecipeConfig实体对象,然后遍历每个字段和Parameter对象来检查其是否已存在于数据库中。有一个更好的方法吗?谢谢!