2

我有一个简单的实体类,它应该包含唯一的名称

@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; }
}

由于大量修改,我想使用延迟写入选项。这是我尝试过的测试及其输出。

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);
} 

输出

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

所以我的问题是,即使它在放置第二个包时抛出异常,为什么它会列出两个包。有什么方法可以在不使用事务的情况下避免这种情况?

谢谢。

4

0 回答 0