【问题标题】:How to create composite key in Objecty?如何在对象中创建复合键?
【发布时间】:2015-01-06 13:48:38
【问题描述】:

我要使用 Objectify 在 GAE 数据存储中创建以下 Entity

@Entity
class TestEntity {

    Long deviceId;
    Long userId;
    boolean status

}

在这里,我不能将 deviceIduserId 作为主键 (@Id),因为它们之间存在多对多关系。所以,我想把deviceIduserId的组合作为主键,避免重复条目。

我不知道该怎么做。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: google-app-engine google-cloud-datastore objectify


    【解决方案1】:

    如果您真的想将键创建为 deviceIduserId 的组合,您可以创建包含此类值的附加字段。

    @Entity
    class TestEntity {
        @Id
        String key;
        Long deviceId;
        Long userId;
        boolean status
    
        public TestEntity(Long deviceId, Long userId) {
            key = deviceId.toString() +"|" +userId;
            //its better to separate them to avoid conflict
            //{123,1} vs {12,31}
            ...
        }
    }
    

    【讨论】:

    • 最好加个分隔符,这样{123,1}和{12,31}就不会冲突了。
    • @stickfigure 是的,你是对的,我没有想过这个。当然,建议在这些值之间使用某种分隔符以使键唯一。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 2011-09-16
    • 1970-01-01
    • 2016-11-21
    相关资源
    最近更新 更多