Question

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 am saving two object s1 and s2 in DB4o Database and both object are saved even though they have duplicate information , what I want is same rollNo student should be saved only once just like relational databases using primary key. I know that DB4o save objects based on reference address, correct me if I am wrong. Please let me know if there is any way to achieve primary key functionality to avoid Data Redundancy in DB4o.

Thanks

Was it helpful?

Solution

db4o tracks object by their identity. So if you create a new object with 'new', it will be considered a new object. If you want to update a object, you need to get that object and change it. 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

That's it. db4o allway's tracks the actual objects. Not the values.

Note that you can add unique constrains to avoid mistakes. For more about updating, see documentation: http://community.versant.com/documentation/reference/db4o-8.1/java/reference/Content/basics/update_concept.htm

OTHER TIPS

Basically you have 2 options:

  1. Add a UniqueFieldValueConstraint to your configuration (in this case violations will be reported as exceptions)

  2. Execute a query (which is basically what the UniqueFieldValueConstraint will do anyway) and check if such object already exists in the db.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top