I'm having difficulty determining the best approach for modifying a discriminator value after the record has been inserted when using a table per class hierarchy approach. The example that I will use is the Payment mapping from the Hibernate documentation.
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="PAYMENT_TYPE" type="string"/>
<property name="amount" column="AMOUNT"/>
...
<subclass name="CreditCardPayment" discriminator-value="CREDIT">
<property name="creditCardType" column="CCTYPE"/>
...
</subclass>
<subclass name="CashPayment" discriminator-value="CASH">
...
</subclass>
<subclass name="ChequePayment" discriminator-value="CHEQUE">
...
</subclass>
</class>
Now let's say that I insert a CashPayment into the table with the pseudo code below.
Code:
CashPayment payment = new CashPayment();
payment.setAmount(2.50);
session.save(payment);
A record is successfully written to the DB. Then when I retrieve the record, the instance is a CashPayment as expected.
Code:
Payment payment = session.get(Payment.class, 1234);
Now here's my problem The user interface that I am building allows the payment type to be changed from a cash payment to a credit card payment (this is theoretical). There doesn't seem to be an easy way to do this. One approach is to manually update the database value, but I am trying to avoid that because I cannot guaurantee that the user will want to permanently save the value from the interface. The other approach that I've tried is to create a new CreditCardPayment instance and copy to the attributes from the cash instance to the credit instance.
Code:
Payment payment = session.get(1234);
CreditCardPayment newPayment = new CreditCardPayment ();
newPayment.setAmount(payment.getAmount());
session.evict(payment);
session.save(newPayment);
This performs an update but does not update the discriminator value. And also I am not extremely happy with the approach but could live with it.
Does anyone have any solutions that have worked well for them in the past?