2

I have a simple entity class and it is supposed to include unique names on it.

@Entity
class Package {
    @PrimaryKey(sequence = "ID")
    public Long id;

    @SecondaryKey(relate = Relationship.ONE_TO_ONE)
    public String name;

    private Package() {}

    public Package(String name) { this.name = name; }

    @Override
    public String toString() { return id + " : " + name; }
}

I want to use deferred writing option because of extensive modification. Here is the test i tried and its output.

final String dbfilename = "test01";
new File(dbfilename).mkdirs();
EnvironmentConfig config = new EnvironmentConfig().setAllowCreate(true);
Environment environment = new Environment(new File(dbfilename), config);
StoreConfig storeConfig = new StoreConfig().setAllowCreate(true).setDeferredWrite(true);
EntityStore store = new EntityStore(environment, "", storeConfig);

PrimaryIndex<Long, Package> primaryIndex = store.getPrimaryIndex(Long.class, Package.class);

try {
    primaryIndex.put(new Package("package01")); // will be put.
    primaryIndex.put(new Package("package01")); // throws exception.
} catch (UniqueConstraintException ex) {
    System.out.println(ex.getMessage());
}

store.sync(); // flush them all

// expecting to find one element
SortedMap<Long,Package> sortedMap = primaryIndex.sortedMap();
for (Package entity : sortedMap.values()) {
    System.out.println(entity);
} 

Output

(JE 5.0.73) Unique secondary key is already present
1 : package01
2 : package01

So my question is that even if it throws exception while putting second package, why does it lists two packages. Any way to avoid this without using transactions?

Thanks.

Akdeniz
  • 1,260
  • 11
  • 21

0 Answers0