这是我的实体
@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/