gpt4 book ai didi

java - 如何使用 spring-data-jpa mongoRepository 进行查询和更新?

转载 作者:行者123 更新时间:2023-12-02 08:57:07 29 4
gpt4 key购买 nike

这是我的实体

@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

关于java - 如何使用 spring-data-jpa mongoRepository 进行查询和更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60431577/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com