Spring Data JPA 更新行而不获取行 ById
Posted
技术标签:
【中文标题】Spring Data JPA 更新行而不获取行 ById【英文标题】:Spring Data JPA update a Row without getting the row ById 【发布时间】:2019-09-05 14:33:05 【问题描述】:我想使用 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;
我有一个低于Json Input
的PutMapping
Spring boot API
"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
对象,然后在其之上进行更新?这使得代码每次更新都连接数据库两次。
请提出您的意见
【问题讨论】:
RTFM 【参考方案1】:我会首先使用updatedId
获取参考对象
RewardEntity rewardEntity = rewardRepository.getOne(updatedId )
根据您的要求更新此对象
rewardEntity.setLastModifiedDate(OffsetDateTime.now());
最后使用 save 来更新它。
return rewardRepository.save(rewardEntity);
getOne()
返回对实体的引用并在内部调用EntityManager.getReference()
方法。它总是会返回一个代理而不访问数据库(延迟获取)。
【讨论】:
以上是关于Spring Data JPA 更新行而不获取行 ById的主要内容,如果未能解决你的问题,请参考以下文章