I want to update/insert an entity, depending not on primary key but on equals:
@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();
If equals alert exists (e.g., with field1="foo", field2="bar" and field3=null), I want to update its lastOccurence, else insert the new alert.
(Of course, I could use a nasty derived query method like findByField1AndField2AndField3...)
If you're using spring, you can take advantage of Example
. Assume you have an AlertReporitory
that implements JpaRepository
, then you can do the following:
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
}