我想使用spring-jpa更新表
这是我的实体类
public class RewardEntity {
@Id
@Column(name = "reward_id", columnDefinition = "bigserial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long rewardId;
@Column(name = "reward_title", nullable = false)
private String rewardTitle;
@Column(name = "reward_text")
private String rewardText;
@Column(name = "reward_type", nullable = false)
private String rewardType;
@Column(name = "reward_for_code", nullable = false)
private String rewardFor;
@Column(name = "reward_from_date", nullable = false)
private OffsetDateTime rewardFromDate;
@Column(name = "reward_to_date", nullable = false)
private OffsetDateTime rewardToDate;
@Column(name = "is_display_on", nullable = false)
private Boolean isDisplayOn;
@Column(name = "created_id", length = 50, nullable = false)
private String createdId;
@Column(name = "updated_id", length = 50)
private String updatedId;
@Column(name = "created_date", columnDefinition = "timestamptz", nullable = false)
private OffsetDateTime createdDate;
@Column(name = "last_modified_date", columnDefinition = "timestamptz")
private OffsetDateTime lastModifiedDate;
}
我有一个PutMapping
春季靴子API
,低于Json Input
{
"rewardId": 53,
"rewardTitle": "Reward is Allocated",
"rewardText": "Reward allocated for your recent purchase with our shop located at ABC-Mall",
"rewardType": "Informational",
"rewardFor": "Customer",
"rewardFromDate": "2019-04-12T00:00:00+05:30",
"rewardToDate": "2019-04-15T00:00:00+05:30",
"isDisplayOn": false
}
我的控制器将Principal
对象用于创建 和更新 rewards
表
@PutMapping
public ResponseEntity<RewardsResponse> updateRewards(Principal updatedPrincipal,
@RequestBody RewardUpdateRequest RewardUpdateRequest) {
但是我不会从Angular-UI发送我的createdId
或updatedId
。因此,当我尝试使用以下服务层代码将更新的实体插入表中时
public RewardEntity updateReward(Principal principal, rewardEntity rewardEntity) {
String updatedId = null != principal ? principal.getName() : "defaultUpdatedId";
rewardEntity.setUpdatedCdsId(updatedId);
rewardEntity.setLastModifiedDate(OffsetDateTime.now());
return rewardRepository.save(rewardEntity);
}
我收到以下错误
could not execute statement; SQL [n/a]; constraint [created_id]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
我的假设是,通过映射我们传递的RewardEntity
并仅更新我设置的ID
而不涉及其余字段,可以在同一行中更新fields
。 ..
我应该首先根据ID从数据库中获取我的RewardEntity
对象,然后在其之上进行更新吗?这样,代码每次更新都会两次连接数据库。
请输入您的意见
答案 0 :(得分:1)
我首先要使用updatedId
RewardEntity rewardEntity = rewardRepository.getOne(updatedId )
根据您的要求更新此对象
rewardEntity.setLastModifiedDate(OffsetDateTime.now());
最后使用save进行更新。
return rewardRepository.save(rewardEntity);
getOne()
返回对该实体的引用,并在内部调用EntityManager.getReference()
方法。它将始终返回代理,而不会访问数据库(延迟获取)。