Java OneToMany, ManyToOne, OneToOne

javajpa

In JPA (Java Persistence API), a OneToMany relationship refers to a relationship between two entities where one entity has a @OneToMany annotation and the other entity has a @ManyToOne annotation. This relationship represents a one-to-many relationship between the two entities, where one entity has a collection of the other entity.

A OneToOne relationship refers to a relationship between two entities where one entity has a @OneToOne annotation and the other entity has a @OneToOne annotation. This relationship represents a one-to-one relationship between the two entities, where each entity has a reference to a single instance of the other entity.

To create a OneToMany relationship in JPA, you need to define the relationship on the side of the entity that has the many-to-one relationship. For example:

@Entity
public class Parent {
    @Id
    private Long id;

    @OneToMany(mappedBy = "parent")
    private List<Child> children;
    // other fields and methods
}

@Entity
public class Child {
    @Id
    private Long id;

    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;
    // other fields and methods
}

To create a OneToOne relationship in JPA, you need to define the relationship on both sides of the relationship. For example:

@Entity
public class Employee {
    @Id
    private Long id;

    @OneToOne(mappedBy = "employee")
    private Address address;
    // other fields and methods
}

@Entity
public class Address {
    @Id
    private Long id;

    @OneToOne
    @JoinColumn(name = "employee_id")
    private Employee employee;
    // other fields and methods
}

In both cases, the @JoinColumn annotation specifies the name of the column in the database table that represents the foreign key for the relationship.