Search code examples
springspring-data-jpaspring-datamany-to-many

How to add column with instant in many-to-many mapping?


everyone! I have to tables "market" and "customer" with many-to-many mapping. Hibernate automatically create table post_comment table with id and then I can get objects and everything ok...but I need the date when a customer by something in the market enter image description here

market class

@Entity
@Setter
@Getter
@NoArgsConstructor
public class Market{

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

    @ElementCollection(targetClass = Customer.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "market_customer", joinColumns = @JoinColumn(name = "market_id"))
    private Set<Customer> banks = new HashSet<>();
    
    ............
}

market class

@Entity
@Setter
@Getter
@NoArgsConstructor
public class Customer{

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

I can create automatically marcet_customer with only ids but I can't understand how to add date and most importantly how to get it by JPA repository...


Solution

  • That's the thing with the Hibernate @ManyToMany - it's not meant to have extra columns nor to be queryable (very well). Maybe you want to go with a separate Entity with a composite primary key:

    @Entity(name = "MarketCustomer")
    @Table(name = "market_customer")
    public class MarketCustomer {
    
        @EmbeddedId
        private MarketCustomerId id;
    
        @ManyToOne(fetch = FetchType.LAZY)
        @MapsId("marketId")
        private Market market;
    
        @ManyToOne(fetch = FetchType.LAZY)
        @MapsId("customerId")
        private Customer customer;
    
        ...
    }
    
    @Embeddable
    public class MarketCustomerId implements Serializable {
    
        @Column(name = "market_id")
        private Long marketId;
    
        @Column(name = "customer_id")
        private Long customerId;
    
        ...
    }
    

    A good article on this https://vladmihalcea.com/the-best-way-to-map-a-many-to-many-association-with-extra-columns-when-using-jpa-and-hibernate/ . With https://bootify.io you can create your schema online as well (no composite primary key, but a separate primary column is doing fine as well).