views:

19

answers:

1

I am making a POS like system. I wonder how to map subclass using JPA (this is for my DAO). Product class has product details and OrderProduct class has information about the Product and details about the order.

@Entity
@Table(name="products")
public class Product implements Serializable{
    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.AUTO
    public int getId(){ return id;}

    /**
     Other get/set methods
    */
}

@Entity
@Table(name="order_products")
public class OrderProduct extends Product{
        @Id
        @Column(name="id")
        @GeneratedValue(strategy = GenerationType.AUTO)
        public int getId(){ return id;}

        /**
         Other get/set methods
        */
}

I got complain about duplicate @Id. But OrderProduct class really need another id than the product one. How should I map this?

DB is something like this

Table products
id int
name varchar(32)

Table order_product
id int
quantity int
productid int fk referencing product table

Would @IdClass or @AttributeOverride help?

+1  A: 

I don't think that what you'd like to achieve is possible neither with JPA nor Hibernate. When using a joined subclass strategy, the PK of the subclass is the the PK of the base class and is used to perform the join between the tables. From the JPA specification:

2.1.10.3 Joined Subclass Strategy

In the joined subclass strategy, the root of the class hierarchy is represented by a single table. Each subclass is represented by a separate table that contains those fields that are specific to the subclass (not inherited from its superclass), as well as the column(s) that represent its primary key. The primary key column(s) of the subclass table serves as a foreign key to the primary key of the superclass table.

You could use a @PrimaryKeyJoinColumn to change the column name in the child class:

@Entity
@PrimaryKeyJoinColumn(name="PRODUCT_ID", referencedColumnName = "ID")
public class OrderProductTop extends ProductTop {
    ...
}

But PRODUCT_ID would still be the PK.

And to be honest, I don't understand your physical model. To me, what you currently have represented is a one-to-many relationship, which is not correct (it should be a one-to-one).

Pascal Thivent