I have a table with a composite primary key of the following structure:
create table follows (
source_id bigint references users on delete cascade,
target_id bigint references users on delete cascade,
created_at timestamptz not null default now_utc(),
primary key ( source_id, target_id ),
constraint source_and_target_differ
check ( source_id <> target_id )
);
However, when I try to create a new entity twice with 2 identical POST requests (which causes a constraint error on the DB side and it doesn't let the request through when I try to manually execute the SQL) it doesn't fail: it sends me the correct response first time, and an incorrect response all following times, but not an error.
My JPA entity looks the following way:
@Entity
@Table(name = "follows")
@IdClass(FollowPK.class)
@Follow.SourceAndTargetAreNotEqual // Custom validator
public class Follow {
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "source_id", nullable = false)
private User source;
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "target_id", nullable = false)
private User target;
@Column(nullable = false, insertable = false, updatable = false)
@Generated
@Temporal(TemporalType.TIMESTAMP)
private LocalDateTime createdAt;
// Getters, Setters, etc by Lombok
}
public static final class FollowPK implements Serializable {
private Long source;
private Long target;
}
I was wondering if I could use some Hibernate/Spring setting to fix this, or maybe use @RepositoryEventHandler and @HandleBeforeSave