M
M
MaNuN2022-03-11 20:00:48
Java
MaNuN, 2022-03-11 20:00:48

Hibernate how to add and display in essence an additional column in the binding ManyToMany table?

Good day, please tell me how to solve this problem correctly:
I have 2 entities

  • Products
    • id
    • Name
    • cost
    • Category

  • Transactions
    • id
    • List (Product)



The relationship between them is Many to many, that is, the transaction_product table has been created with the following fields:
  • transaction_id
  • product_id

respectively.

entity classes look something like this:
product

@Entity
@Table(name = "products")
public class Product {
  
  @Id
  @Column(name = "id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private int id;
  
  @Column(name = "name")
  private String name;
  
  @ManyToOne(cascade = {CascadeType.DETACH,CascadeType.MERGE,CascadeType.REFRESH}, fetch = FetchType.LAZY)
  @JoinColumn(name = "category")
  private Category category;
  
  @Column(name = "cost")
  private Double cost;
//constructor getter setter
}



transaction

@Entity
@Table(name = "transactions")
public class Transaction {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;



    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH},
            fetch = FetchType.LAZY)
    @JoinTable(
            name = "transactions_products",
            joinColumns = @JoinColumn(name = "product_id"),
            inverseJoinColumns = @JoinColumn(name = "transaction_id")
    )
    private List<Product> products;
//constructor getter setter
}



Here I needed to add another "quantity" column that displays the number of specific products in a transaction. It is most logical to add transaction_product to the table - but here is a stupor, but how to display it in java?
Probably something like this?
private List<Map<Product, Integer>> products;
but how to connect it with hibernate?

or shouldn't it be done?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2022-03-12
@vsafonin

Good afternoon.
I recently answered a similar question:
https://qna.habr.com/q/1114434

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question