【问题标题】:Foreign Key in Berkeley DBBerkeley DB 中的外键
【发布时间】:2014-04-15 01:26:32
【问题描述】:

我有两个实体:

第一个是:

public class WordEntity {
    @PrimaryKey
    private String content;

    private int wordId;
}

第二个是:

public class LexiconEntity {
    @SecondaryKey(relate = Relationship.ONE_TO_ONE, relatedEntity = WordEntity.class)// it does not work
    private int wordId;

    private int numDocs;
}

我想将LexiconEntity 的wordId 作为WordEntity 的外键。我该怎么做?

【问题讨论】:

  • LexiconEntity 不应该也有 PrimaryKey 吗?编译器是否产生任何错误?

标签: java database foreign-keys berkeley-db berkeley-db-je


【解决方案1】:

迟到的答案,但是...首先,对于 WordEntity,wordId 看起来会是更自然的 PK。 LexiconEntity 还应该定义一个 PrimaryKey。 WordEntity 应该定义引用 LexiconEntity 的 SecondaryKey 或“指定与该实体相关的实体”。

public class WordEntity {
    @PrimaryKey
    private int wordId;
    private String content;
    @SecondaryKey(relate = Relationship.ONE_TO_ONE, relatedEntity = LexiconEntity.class)
    private int lexId;
}

public class LexiconEntity {
    @PrimaryKey
    private int lexId;
    private int numDocs;
}

因此数据为:

词典实体: lexId ----- 100 101 102 字实体: wordId lexId ------ ----- 1 100 2 101 3 102

由于关系是 one_to_one,因此辅助键对于定义它的对象是唯一的。所以在这种情况下,lexId 在 WordEntity 中是唯一的,所以你不能拥有:

字实体: wordId lexId ------ ----- 1 100 2 101 3 100 -- 插入异常,因为它是重复的

见http://docs.oracle.com/cd/E17277_02/html/GettingStartedGuide/dplindexcreate.html#dplsecondaryidxdecl http://docs.oracle.com/cd/E17277_02/html/java/com/sleepycat/persist/model/SecondaryKey.html#relatedEntity()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多