martes, 21 de junio de 2022

Spring Data Jpa Entity RelationShip Mappings @OneToMany Unidirection (No middle table)

Spring Data Jpa Entity RelationShip Mappings @OneToMany Unidirection (No middle table)



Java Entities

PurchaseOrder Entity


@Entity
@Data
@NoArgsConstructor
@NamedQuery(name="PurchaseOrder.findById_named", query = " FROM PurchaseOrder p JOIN FETCH p.items i WHERE p.id = :id")
@Table(name = "purchase_order", schema = "public")
public class PurchaseOrder {
@Id
@GeneratedValue(strategy = GenerationType.AUTO,generator = "public.purchase_order_seq")
private Long id;
private String name;
@OneToMany( cascade = CascadeType.ALL, targetEntity = Item.class) //default targetEntity can be omitted
@JoinColumn(name = "purchase_order_id_fk", // default is "item.items_id" And Avoids the creation of extra Table
referencedColumnName = "id") // default could be omitted
private List<Item> items = new ArrayList<>();


Item Entity


@Entity
@Data
@NoArgsConstructor
@Table(name = "item", schema = "public")
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.AUTO,generator = "public.item_seq")
private Long id;
private String name;


Hibernate creates automatically the tables the next way

Hibernate: 
    
    create table public.item (
       id int8 not null,
        name varchar(255),
        purchase_order_id_fk int8,
        primary key (id)
    )
Hibernate: 
    
    create table public.purchase_order (
       id int8 not null,
        name varchar(255),
        primary key (id)
    )
Hibernate: 
    
    alter table if exists public.item 
       add constraint FK1ohvucgh093bf3fnpbhhitv47 
       foreign key (purchase_order_id_fk
       references public.purchase_order

Test the behaviour


eot

No hay comentarios:

Publicar un comentario