Search code examples
javasqlmappingjpa-2.0openjpa

How to mapping the relationship Store <- Stock -> Product with OpenJPA?


I have the next relationship:

Relationship

Currently, I have the next code:

@Embedded
public class StockPK implements Serializable {

    private int storeId;

    private int productId

}

@Entity
public class Stock implements Serializable {

    @EmbeddedId
    private StockPK id;

    private int cantidad;

    @ManyToOne
    private Store store;

    @ManyToOne
    private Product product;

}

But the DDL generated (I'm using OpenJPA in TomEE) adds two aditional fields.

CREATE TABLE STOCK (
    productId  INTEGER NOT NULL,
    storeId    INTEGER NOT NULL,
    quantity   INTEGER NOT NULL,
    PRODUCT_ID INTEGER         ,
    STORE_ID   INTEGER         ,
    PRIMARY KEY (productId, storeId)
)

How should specify this relationship?


Solution

  • Thanks JBNizet :) — The solution was as follows:

    @Embeddable
    public class StockPK implements Serializable {
    
        @Column(name = "store_id")
        private int storeId;
    
        @Column(name = "product_id")
        private String productId;
    
        // Getters, setters, hashCode, equals
    
    }
    
    @Entity
    @Table(name = "stock")
    public class Stock implements Serializable {
    
        @EmbeddedId
        private StockPK id;
    
        @MapsId("storeId")
        @ManyToOne
        private Store store;
    
        @MapsId("productId")
        @ManyToOne
        private Product product;
    
        @Column(nullable = false)
        private int quantity;
    
        // Getters, setters
    
    }
    
    @Entity
    @Table(name = "store")
    public class Store implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
    
        // Other fields, getters, setters ...
    
    }
    
    @Entity
    @Table(name = "product")
    public class Product implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
    
        // Other fields, getters, setters ...
    
    }