Reputation: 23
I'm trying to work out if there is a better way of doing the insert/update in the following scenario. I have two classes:
public class Person {
private int id;
private String firstName;
private String lastName;
private Family family;
...
}
public class Family {
private int id;
private String name;
...
}
The primary key in both is Id (which I would like to keep that way for the purpose of this exercise). There is a many-to-one relationship between person and family, so many people can have the same family. My input method allows you to set any family value but I check before the insert to see if it exists:
public void savePerson(Person person) {
System.out.println("Saving person");
Family existingFamily = getFamily(person.getFamily().getName());
if (existingFamily != null) {
person.setFamily(existingFamily);
}
sessionfactory.getCurrentSession().saveOrUpdate(person);
}
...
public Family getFamily(String name) {
System.out.println("Getting family: " + name);
Family family
= (Family) sessionfactory.getCurrentSession().createQuery("from Family where name = :name")
.setParameter("name", name)
.uniqueResult();
return family;
}
My question is then can this be done automagically somehow through hibernate (which I am somewhat new to) or do I always need to check the database for an existing object beforehand (and update the Person)?
Cheers
Hojo
Upvotes: 2
Views: 264
Reputation: 1331
You can check for existing object by using get()
method rather than writing HQL query
Example:
public boolean getFamily(int famId) {
Family family = (Family)sessionfactory.getCurrentSession().get(Family.class,famId);
if(family!=null){
return true;
}
else{
return false;
}
}
This is how I do in my projects.get()
method returns Object if it present in DB else returns null.
Upvotes: 1