cant understand @joincolumn(name="user_id")

39 views Asked by At

i have created two seperated class in entity,

varibale declared in user class is :

private Long id;
private String name;

variable declared in book class is:

private Long id;
private String title;
private String author;
private boolean borrowed;
@ManyToOne
@JoinColumn(name = "user_id")
private User borrowedBy;

i cant understand @JoinColumn and what is user_id ? and explain me how @manytoone works?

1

There are 1 answers

0
Timur Celikel On

If you look at the typical JPA logs with Hibernate DDL type of 'create' you can see what is happening behind the scenes:

create table book (
    borrowed boolean not null,
    id bigint generated by default as identity,
    user_id bigint,
    author varchar(255),
    title varchar(255),
    primary key (id)
)

 create table user (
    id bigint generated by default as identity,
    name varchar(255),
    primary key (id)
)

JPA will create a column (if it doesn't already exist and depending on the DDL type) in your Book table called user_id. This will be the column that holds the identifier to join to the user table.

You can even see that Hibernate creates a foreign key constraint for us auto-magically:

alter table if exists book 
   add constraint FK1wxwagv6cm3vjrxqhmv884hir 
   foreign key (user_id) 
   references user

By default, unless specified the user_id column in the book table will contain the primary key values of the user table. In our case, the value defined in the User class id field.

I've included the entities for both User and Book here:

@Entity
@Data
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String title;
    private String author;
    private boolean borrowed;
    @ManyToOne
    @JoinColumn(name = "user_id")
    private User borrowedBy;
} 

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
}