David
David

Reputation: 37

How to make a Table without an @Id Column?

Here's I've got 2 main independant tables, user & detail, and a 3rd one that link each other users_details with two foreign keys as follow:

+-----------+------------------+------+-----+---------+-------+
| Field     | Type             | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| user_id   | int(10) unsigned | NO   | MUL | NULL    |       |
| detail_id | int(10) unsigned | NO   | MUL | NULL    |       |
+-----------+------------------+------+-----+---------+-------+

To implement this in Spring Data JPA, I'm using this class which displays the error Persistent entity 'UsersDetails' should have primary key:

@Data
@Entity
@Table(name = "users_details")
public class UsersDetails {

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "detail_id")
    private Detail detail;
}

Since I don't have any primary key, how should I bypass this?

Or, should I make one even if it's not used?

Upvotes: 1

Views: 1894

Answers (1)

Augusto
Augusto

Reputation: 29977

You don't need to map the table users_details. You can let JPA manage it automatically by defining a many-to-many relationship.

You can see a couple of examples here in case you want to map it unidirectionally or bidirectionally.

If you do want to map it for whatever reason, the way to map it is to make a composite key with both values (the typical way to design a many-to-many relationship table). All JPA entities must have an id, so you cannot avoid not having an id. The repo above has an example of a composite key. You'll need to annotate the fields with @Id and provide a Composite key class with @IdClass.

Upvotes: 3

Related Questions