【问题标题】:Spring Data upsert by equalsSpring Data upsert by equals
【发布时间】:2020-05-06 13:15:54
【问题描述】:

我想更新/插入一个实体,不依赖于主键,而是依赖于:

@Entity
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Builder
class Alert {
    @Id
    @Basic(optional = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "field1")
    @EqualsAndHashCode.Include
    private String field1;

    @Column(name = "field2")
    @EqualsAndHashCode.Include
    private String field2;

    @Column(name = "field3")
    @EqualsAndHashCode.Include
    private String field3;

    @Column(name = "last_occurrence")
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastOccurrence;
}

Alert alert = Alert.builder().field1("foo").field2("bar").lastOccurence(new Date()).build();

如果存在 equals 警报(例如,使用 field1="foo"、field2="bar" 和 field3=null),我想更新其 lastOccurence,否则插入新警报。

(当然,我可以使用像 findByField1AndField2AndField3 这样讨厌的派生查询方法...)

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: java spring hibernate spring-data hibernate-mapping


【解决方案1】:

如果您使用的是 spring,则可以利用 Example。假设您有一个实现JpaRepositoryAlertReporitory,那么您可以执行以下操作:

Alert alert = Alert.builder().field1("foo").field2("bar").lastOccurence(new Date()).build();
Optional<Alert> dbAlert = alertRepository.findOne(Example.of(alert));
if (dbAlert.isPresent()) {
    // update
} else {
    // insert
}

【讨论】:

  • 我将它与 ExampleMatcher.withIgnorePaths 和 withIncludeNullValues 结合使用,它解决了我的问题。
猜你喜欢
  • 2015-03-16
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2017-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多