Hi,
I've got an entity which is referenced by many other entities (rows). This entity is somehow immutable in fact. It means that if I want to change even one property value I have to create a new entity or use an existing persistent object with the desired values. Despite of the immutability I provided the setter methods because it should allow a better usage of this class.
Here is an example:
Code:
@Entity
class Product {
....
@ManyToOne
ProductModel poperties;
}
// my "immutable" class
@Entity
class ProductModel {
@Id
Integer id;
int height;
int width;
int weight;
String color;
String someOtherProperty;
// constructor using fields
ProductModel(int height, int width, ....) {}
// getters
// setter to allow better usage
void setHeight(int newHeight) {
this.height = newHeight;
this.id = null;
}
}
There are millions of products but only a few hundreds of product models.
A change to one products model must not influence any other product that originally have the same model.
Now my use case:
I have a product and I want to edit its model to adjust e.g. the color. I don't know if there is already some model with exactly the same values and the desired color. So I should do this:
1. try to find an existing model with desired values
2. if exist load and set this to my product
3. if none exists create new and set it to product
4. save the product
But I want to use it in a different way. Simply let the user edit the current product model and let the system decide whether it is matching some existing product model or a new one that should be persisted.
It should work like this.
1. get a product
2. edit its model (calling any setter would cause the ProductModel id to become null)
3. save the model
During save there is no ID of the product model, so Hibernate should try to find the ID value by the model property values. If one is find, ok associate it with the product. If no matching row, then do an insert.
If I try this now I think that I get a unique constraint violation exception in case there is already a matching row present, because Hibernate is performing an insert when there is null ID.
I thought about select-before-update but I guess it won't provide this funcionality for me.
So I think that I should create a custom EntityPersister. Is it right?
What methods (to override) should I focus on?
Thanks a lot
Wenca