How to avoid duplicate objects in DB4o databases
Student s1 = new Student();
s1.rollNo = "44";
s1.name = "kk";
db4o().save(s1);
Student s2 = new Student();
s2.rollNo = "44";
s2.name = "kk";
db4o().save(s2);
Here I save two objects s1 and s2 in the DB4o database, both of which are saved, even though they have duplicate information, what I want is the same rollNo student should be saved only once Just like a relational database that uses a primary key. I know DB4o saves objects based on reference addresses, correct me if I’m wrong. Let me know if there is any way to implement primary key functionality to avoid data redundancy in DB4o.
Thanks
Solution
DB4O tracks objects by their identity. So if you create a new object with ‘new’, it will be considered a new object. If you want to update an object, you need to get that object and change it. So here it is:
Student toUpdate = db4o.query(new Predicate<Student>() {
@Override
public boolean match(Student student) {
return pilot.rollNo.equals("44");
}
}).get(0);
toUpdate.name ="newName";
db4o.store(toUpdate); Updated
That’s it. DB4O always keeps track of the actual object. It’s not a value.
Please note that you can add Unique constrains to avoid errors. For more information about the update, see the documentation: http://community.versant.com/documentation/reference/db4o-8.1/java/reference/Content/basics/update_concept.htm