Search code examples
javajpahsqldb

JPA Entitties, how to join tables


I have three tables

CREATE TABLE "ingredient" (
  "id" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY,
  "ingredient" VARCHAR(50) NOT NULL
);


CREATE TABLE "pizza" (
  "id" INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) PRIMARY KEY,
  "pizza" VARCHAR(50) NOT NULL
);


CREATE TABLE "pizza_structure" (
  "pizza_id" INT NOT NULL,
  "ingredient_id" INT NOT NULL,
  "amount" INT NOT NULL
);

how to join them, to get Pizzas structure as a Map

@Entity
@Table(name = "ingredient")
public class Ingredient{

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

    private String name;

    public Ingredient() {
    }
}


@Entity
@Table(name = "pizza")
public class Pizza {

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @OneToMany ????
    private Map<Ingredient, Integer> pizzaStructure;

    public Pizza() {
    }

    public Pizza(String name, Map<Long, Integer> pizzaStructure) {
        this.name = name;
        this.pizzaStructure = pizzaStructure;
    }
}

do I need to create @Embeddable class PizzaStructure, if yes when how to use it?

now I'm getting an error Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class:


Solution

  • how to join them, to get Pizzas structure as a Map

    It seems to look like this:

    @ElementCollection
    @CollectionTable(name = "pizza_structure", joinColumns = {@JoinColumn(name = "pizza_id")})
    @Column(name = "amount")
    @MapKeyJoinColumn(name = "ingredient_id")
    private Map<Ingredient, Integer> pizzaStructure;
    

    do I need to create @Embeddable class PizzaStructure

    No.

    More info is here: Hibernate User Guide - Maps.

    Note that table pizza_structure should have foreign keys to pizza and ingredient tables and also unique constrain of pizza_id and ingredient_id, like this (it's postgresql dialect):

    create table pizza_structure
    (
      pizza_id ... constraint fk_structure_pizza references pizza,
      ingredient_id ... constraint fk_structure_ingredient references ingredient,
      amount ...,
      constraint pizza_structure_pkey primary key (pizza_id, ingredient_id)
    );