Java – how to avoid duplicate objects in a db4o database
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. Even if they have duplicate information, I also save the two objects. What I want is that the same rollno student should only save them once, just like the relational database using the primary key. I know that db4o saves objects according to the reference address, If I am wrong, correct me. If there is any way to implement the primary key function to avoid data redundancy in db4o, please let me know
thank you
resolvent:
Db4o tracks objects by their identity. Therefore, if you use "new" to create a new object, it will be regarded as a new object. If you want to update the object, you need to get the object and make changes. So here:
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
Just. Db4o allway tracks actual objects. Not values
Note that you can add unique constraints to avoid errors. For more information about updates, please refer to the documentation: http://community.versant.com/documentation/reference/db4o-8.1/java/reference/Content/basics/update_ concept.htm