'Hibernate: How to create multi-column index on join table

I have two entity classes:

Taco

@Data
@Entity
@Table(name="Taco")
public class Taco {
    
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @SequenceGenerator(name="taco_generator", sequenceName = "taco_seq")
    private Long id;
    
    private Date createdAt = new Date();
    
    @NotNull
    @Size(min=5, message="Name must be at least 5 characters long")
    private String name;
    
    @NotNull
    @Size(min=1, message="You must choose at least 1 ingredient")
    @OneToMany()
    private List<Ingredient> ingredients;
}

Ingredient

@Data
@Entity
@Table(name="Ingredient")
@AllArgsConstructor
@NoArgsConstructor(access=AccessLevel.PRIVATE, force=true)
public class Ingredient {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String id;
    private String name;
    
    @Enumerated(EnumType.STRING) 
    private Type type;
    
    public enum Type {
        WRAP, PROTEIN, VEGGIES, CHEESE, SAUCE
    }
}

Hibernate creates a join table Taco_Ingredient for the given entities. I want to have multiple ingredients for a single taco.

So my Taco_Ingredient will look like this for a single Taco:

enter image description here

As they are not a multi-column key, Hibernate throws an exception when it tries to add another Taco, as the Ingredient will be duplicate.

o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry 'LETC' for key 'Taco_Ingredient.UK_d8e4c1x7i3f3dmm4qemgcoi5y'

I am aware of @Index annotation, but as this join table is auto generated by Hibernate, I do not know how to add multi-column index to this join table.



Solution 1:[1]

In order to specify a one-to-many relationship with join column, you can do as follows:

  @OneToMany(mappedBy = "taco", targetEntity = Ingredient.class)
  private List<Ingredient> ingredients;

  @JsonIgnore
  @ManyToOne
  @JoinColumn(name = "taco_id") // This is on the bearer side
  private Taco taco;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Enfield li