Making a simple relational table in JPA

1 day ago 3
ARTICLE AD BOX

I have a table that in PostgreSQL looks like this:

CREATE TABLE member_block ( member_id INT NOT NULL REFERENCES member(id), block_id INT NOT NULL REFERENCES member(id), CONSTRAINT different_ids CHECK (member_id != block_id), PRIMARY KEY(member_id, block_id) );

How to map this to JPA?

I know I could do something like:

@Entity public class MemberBlock { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @OneToOne @JoinColumn(referencedColumnName = "ID") Member blocker; @OneToOne @JoinColumn(referencedColumnName = "ID") Member blocked; }

But that's not quite it. I'm aware of multiple IDs in JPA, but I don't know if they work with own types:

@IdClass(MemberBlockId.class) @Entity public class MemberBlock { @Id @JoinColumn(referencedColumnName = "ID") Member blocker; @Id @JoinColumn(referencedColumnName = "ID") Member blocked; } record MemberBlockId(Member blocker, Member blocked);

A third idea is to add the blocked members as a @ManyToMany field in Member directly.

All three approaches are missing the constraint as well (so members can't block themselves).

Read Entire Article