0

I must say I found similar topics, but all had oposite map structure, so I decided to create new topic.

I want to use hibernate to connect two tables in many to many relation. Right now it looks like this:

Class product:

@Entity
@Table(name = "PRODUCTS")
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String productName;

    @ManyToMany(mappedBy = "products")
    private Set<Invoice> invoices = new HashSet<>();

    public Product() {};
    public Product(String productName) {
    this.productName = productName;
    }

    public String getName() {
         return this.productName;
    }

    public void addInvoice(Invoice i) {
         this.invoices.add(i);
    }
}

Class invlice, eachinvoice can have many products and each product can be used many times:

@Entity
@Table(name = "INVOICES")
public class Invoice {
     @Id
     @GeneratedValue(strategy = GenerationType.AUTO)
     private int invoiceNumber;

     @ManyToMany
     private Set<Product> products = new HashSet<>();

    public Invoice() {};

    public void addProduct(Product p) {
         products.add(p);
    }
}

Right now I would like to add quantity to invoice, and I think the best option would be a map<Product, int>.

I found some topics on internet, but each one of them had structure like map<String, Object> where we had some key and our object as value.

As far as I know, I bust add to class Product methods equals() and hashCode() for map to even work, but I don't know how to make it work in hibernate (it should work, becouse right now I have extra table that contains product id and invoice id, I would just neet this table to have extra column "quantity"). and I'd appreciate if someone could show me how to do this.

quikq
  • 347
  • 2
  • 13
  • 1
    I think you need [Many-to-Many Association with Extra Columns in Join Table](https://stackoverflow.com/questions/36129040/hibernate-join-table-with-additional-column) instead. – MartinBG Nov 19 '19 at 12:59
  • 1
    Thanks, that's exactly what I was looking for, just couldn't formulate it that way – quikq Nov 20 '19 at 18:05

0 Answers0