2016-03-08 30 views
0

我使用ORM精簡版庫是一個一對多的關係,通過這種方式非常好:Android的ORM建興復合主鍵(兩場)或多對多的關係

@DatabaseTable(tableName = "a") 
class A { 
    @DatabaseField(id = true) 
    private Integer id; 
    ... 
} 

@DatabaseTable(tableName = "b") 
class B { 
    @DatabaseField(id = true) 
    private Integer id; 

    @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "a_id") 
    private A a; 
    ... 
} 

現在,如何創建多對許多關係?我有一些想法,但我不能做這些, 想法 - 我創造了A,B和AB類作爲這樣

@DatabaseTable(tableName = "a") 
class A { 
    @DatabaseField(id = true) 
    private Integer id; 
    ... 
} 

@DatabaseTable(tableName = "b") 
class B { 
    @DatabaseField(id = true) 
    private Integer id; 
    ... 
} 

@DatabaseTable(tableName = "ab") 
class AB { 
    @DatabaseField(id = true) 
    private Integer id; 

    @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "a_id") 
    private A a; 

    @DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = "b_id") 
    private B b; 
} 

我想要做的AB類主鍵(a,b)和刪除id列或make uniuqe(a,b)我可以做任何一個嗎?

回答

1


1.我認爲在ORMLite中實現多對多關係的唯一方法是使用第三個表,就像您建議的一樣。你可以看看這個答案:https://stackoverflow.com/a/9179937/5318705
2.我這次沒有創建複合PK的可能性。但是,無論如何,您可以將虛擬ID字段保留爲PRIMARY KEY並使用uniqueCombo約束:

... 
@DatabaseField(id = true) 
    private Long dummyId; 

@DatabaseField(uniqueCombo = true) 
    private Integer idA; 

@DatabaseField(uniqueCombo = true) 
    private Integer idB; 
...