tags:

views:

127

answers:

2

I have an entity Promotion, which has 3 simple fields (id, name, description) and all 3 will be mapped to DB. So far so good. Problem is with the 4th field, ruleModel, which is an instance of RuleModel and when constructed at runtime, it will contain object instances of a dozen other classes. I don't want to map RuleModel to a DB table, because that is a lot extra work and also unnecessary. I just want to store the ruleModel object instance into DB and then be able to load ruleModel from DB and restore the object instance in memory.

Code:

@Entity  
public class Promotion {  
    @Id  
    @GeneratedValue  
    private Long id;  

    private String name;  
    private String description;  

    private RuleModel ruleModel;

}

A: 

If you make the Rule Model class implement the Serializeable interface then you should be able to add a RuleModel variable to your Promotion class. This would require the addition of a new column to the Promotion table. When you persist the Promotion class the seraralized instance of the RuleModel class instance will be stored in the new column.

instanceofTom
A: 

If I understand correctly, you're trying to serialize the RuleModel instance - which contains references to many other instances - and when you deserialize it you would accept that all of the references ruleModel previously held would be lost. If this is your goal, you need to do two things:

  1. Mark any field in RuleModel with the transient that
  2. Annotate RuleModel with the JPA @Embeddable annotation
  3. Annotate the ruleModel field in Promotion with @Embedded

While this won't persist the ruleModel instance into a single column, it will persist the instance into multiple columns of the same table used by Promotion. It will also reinstantiate ruleModel as you desire.

rcampbell