Having this entities:
User.java:
@Entity
@NoArgsConstructor
@Getter
@Setter
public class User {
@Id
private int id;
private String username;
@OneToMany(mappedBy = "owner")
@MapKey(name = "friend_id")
private Map<User, Friendship> friends = new HashMap<>();
}
Friendship:
@Entity
@Data
//@IdClass(Friendship.class)
public class Friendship implements Serializable {
@Id
private int owner_id;
@Id
private int friend_id;
private String level;
@ManyToOne
@MapsId("owner_id")
private User owner;
@ManyToOne
@MapsId("friend_id")
private User friend;
}
I though I must have @IdClass
or @EmbeddedId
if I want to use two or more primary keys. But as shown above, I could ommit either, and just declare two primary keys (this is what I mean it "compiles"). So the question is, why to even bother using either of those annotations and just declare more keys?
generated table:
+-----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| owner_id | int | NO | PRI | NULL | |
| friend_id | int | NO | PRI | NULL | |
| level | varchar(255) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+