3

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)

1
  • should I just delete all and then re-insert? Commented Jul 15, 2010 at 18:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.