If I persist a class using hibernate, how do I ensure that the values of some fields are merged while others are created?

If cheese type is stored in its own table, you should have a mapping for it. Similarly you should have a mapping for Cheese too, where you define how to map its properties. There you can specify the association between Cheese and CheeseType.

If cheese type is stored in its own table, you should have a mapping for it. Similarly you should have a mapping for Cheese too, where you define how to map its properties. There you can specify the association between Cheese and CheeseType.

For this to work, CheeseType needs an identifier, which uniquely identifies its instances. This allows you to know that two CheeseType objects both having type = "cheddar" are indeed the same logical instance. An obvious possibility is the type field, however it is usually better to use a generated internal ID for this purpose.

For further details, see the chapter Mapping associations in the .

I don't know if this will suit your needs but if you know that you already have a "cedar" CheeckType (assuming CheeseType is an entity and "cedar" is the identifier - your example isn't clear/coherent), then you could use Session#load(), or EntityManager#getReference() if you are using JPA, to set the association when creating a new Cheese, like this: em.getTransaction().begin(); CheeseType type = em. GetReference(CheeseType. Class, "cedar"); // no db hit Cheese cheese = new Cheese(); cheese.

SetType(type); cheese. SetPurchaseDate("01/02/03"); em. Persist(cheese); em.getTransaction().commit(); If you don't know if you already have a "cedar" CheeseType, then you could try a merge indeed.

Here is what the JPA spec, section 3.2.4.1 writes about it: The semantics of the merge operation applied to an entity X are as follows: If X is a new entity instance, a new managed entity instance X1 is created and the state of X is copied into the new managed entity instance X1. So merge will insert/update depending on the state of the entity. But make sure to really understand how merge works (see links below), merging is not an obvious concept IMO.

Resources berante Entity Manager Reference Guide Merging vs. saveOrUpdate/saveOrUpdateCopy When - and when not - to use the JPA merge method Related questions bernate: Difference between session. Get and session. Load JPA EntityManager: Why use persist() over merge()?

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions