[英]How I Use spring-data-jpa mongoRepository to query and update?
這是我的實體
@Document(collection = "deviceConfig")
@Data
@Builder
public class DbDeviceConfig {
private ObjectId _id;
// @Field("id")
// @Id
// private String id;
private String deviceId;
private String enterpriseId;
private Integer state;
private String cfgKey;
@JsonSerialize
private String cfgValue;
private Long cfgDate;
private Long reportDate;
private Integer reportCode;
private String reportMsg;
}
如您所見,我注意到@Id
因為在我的情況下,每個設備只有一個特定 cfgKey 的 cfgValue
因此,enterpriseId 和 deviceId 以及 cfgKey 將保持其唯一性
我寫了 mongotemplate 更新 sql
Query updateQuery = new Query(Criteria.where("enterpriseId").is(enterpriseId)
.and("cfgKey").is(batchAddDeviceConfig.getCfgKey())
.and("deviceId").is(deviceId));
Update update = new Update();
update.set("cfgDate", System.currentTimeMillis());
update.set("cfgValue", batchAddDeviceConfig.getCfgValue());
update.set("state", batchAddDeviceConfig.getState());
dataMongoTemplate.upsert(updateQuery, update, DbDeviceConfig.class, "deviceConfig");
但我不知道如何編寫相應的spring jpa代碼
或者我應該添加一個商業 ID?
我真的很困惑,因為 mongodb 已經創建了一個 ObjectId
我也在尋找其他人的解決方案
看來我可以用這種方式
@Modifying
@Query("UPDATE Space c SET c.owner = :name WHERE c.id = :id")
Integer setNameForId(@Param("name") String name, @Param("id")
但這就像很多參數
請幫我QAQ
如果您使用的是 Spring Data JPA,那么您可以使用repository.findBy....()
方法從數據庫中獲取實體,在獲取的實體中設置更新的值,然后對其調用repository.save(entity)
。 Hibernate 會處理這個問題,它會更新你的實體。 但是它會為所有字段生成更新查詢。 如果只想更新更改的字段,則可以在實體類上使用@DynamicUpdate
。
該線程中的其他答案有問題......如果你 findBy 然后 save 你實際上正在做一些不是原子的事情。 如果您正在尋找一種原子方式來執行此操作,那么您應該記住,最簡單的方法(我認為是唯一的方法)是使用帶有更新功能的 mongo 模板...
在我看來,spring 數據存儲庫選項更像是一個方便的選項。
(在此處編輯為對其中一條評論的回答)
假設您想要執行 $inc 操作。 此操作讀取一個字段,將其遞增並以原子方式將其寫回 DB。 在 spring 中使用 MongoTemplate 這樣做非常容易:
Update update = new Update();
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
update.inc("upvoteCount");
template.updateFirst(query, update, "post");
查詢找到您需要的文檔,然后更新更新它。
我搜索了很長時間,但找不到使用 spring 數據存儲庫執行此操作的方法...
我可能是錯的......但我不認為這樣的方式甚至存在......如果確實如此,我希望有人向我指出
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.