views:

32

answers:

2

Pseudo code to get to the point:

@Entity
Person {
   @Id
   Integer id;
   String SSN;
   String name;
}

Use case for repository, or service:

personRepository.save(new Person(ssn:"123456", name:"jeff")):
  • id is unique and autoincremented primary key
  • SSN is unique and is the identifier of a person
  • name is just a string and could be changed

Currently save uses hibernate's merge() to do the insert/update, but I don't have the id when I'm saving (part of my abstraction layer so that client code doesn't need to touch entities at all), so how can I update the persons name if the SSN is already present in the database without having to do a separate lookup on that field, and then branch logic in there (I don't want to do that because I may be updating and inserting MANY people at once and think it will be slow)

+2  A: 

You could use your session to generate a HQL query, and roll your own update along the lines of:

String queryString = "update Person set name = :name where ssn = :ssn";
Query query = session.createQuery(queryString);
query.setString("name", newName);
query.setString("ssn", ssn);
query.executeUpdate();

I'm not aware of a way to just update an entity as you are suggesting, as Hibernate very heavily depends on your @Id field to aid in determining persisted state.

apiri
Is there any way to make this the default update for an entity? Because I will not always be calling update manually, it could cascade from a parent object. If not, this is likely the best I can do, however I will likely re-evaluate my Entities and come up with something differnt
walnutmon
If the object is properly associated with a parent object in a persistent context AND you have the cascade established on the parent object to the child, Hibernate should handle this automatically for you, updating/creating the appropriate changes where necessary for your child object saying you use a saveOrUpdate from the parent.
apiri
+1  A: 

how can I update the persons name if the SSN is already present in the database without having to do a separate lookup on that field, and then branch logic in there (...)

The only option I can think would be to use the SSN as primary key.

Pascal Thivent