2009-05-26 44 views
3

[編輯:很顯然,這只是針對陣列的問題和FoxyBOA的答案可能直接到(甚至IS)的答案。]爲什麼關聯的集合包含空值? (休眠,註釋,春季)

我的問題涉及到這些軟件:Hibernate3的+註釋,Spring MVC,MySQL,在這個例子中還有Spring Security。

我在想,爲什麼Hibernate自動關聯的集合爲子表的每個行號(除了正確的元素外)都包含空值。我的例子:

我有一個用戶當局表中,用戶用戶名用作外鍵的主鍵。目前,我的權威表中有13行。當我從數據庫中檢索(MySQL的InnoDB的)用戶和Hibernate自動檢索與此對應的映射用戶的權限:

@OneToMany 
@JoinColumn(name = "username") 
@IndexColumn(name="id") // "id" was the primary key and is used to sort the elements 
public Authority[] getAuthorities() { 
    return authorities; 
} 
public void setAuthorities(Authority[] authorities) { 
    this.authorities = authorities; 
} 

...我結束了一個集「部門」含14(0-13)其中只有四個元素不爲null(數據庫表中的四行屬於該特定用戶,因此這是正確的)。至於我意識到,我使用Hibernate的默認像Fetchmode等我收到這樣的用戶屬性:

Criteria criteria = getSession().createCriteria(User.class); 
criteria.add(Restrictions.eq("username",username)); 
User user = (User) criteria.uniqueResult(); 

從org.hibernate.loader.loader正確的日誌記錄信息「中提到」爲四行結果集。但是,創建的用戶在數組中有四個正確的元素加上十個空值。在我的具體例子中,這導致此例外:

java.lang.IllegalArgumentException: Granted authority element 0 is null - GrantedAuthority[] cannot contain any null elements 

回答

2

我可以推薦你檢查你的數據。如果你有一個錯過的索引(在你的案例中是id列),那麼不是錯過了id,你會在你的數組中得到空值。 也就是說

table authorities: 
username id 
bob 1 
bob 3 
bob 5 

因此,你將有一個陣列: {0 =無效,1 =鮑勃,2 =​​零,3 =鮑勃,4 =零,5 =擺錘}

UPDATE: 我遇到的情況有兩種情況:

  1. 缺陣索引列ID鍵值在當局表(例如0,1,3,4,5 - 缺失值2. Hibernate會自動用鍵2和值null在數組中增加一個數組值)。
  2. 索引值是按順序排列的,但是選擇標準過濾其中的一部分(例如,您的HQL類似於「從用戶加入u.authorities a where a.id = 2」那樣的情況。在這種情況下,hibernate加載用戶,但是權威數組您只有3個值:0 - null,1 - null,2 - 具有id 2的權限)。
+0

我添加並刪除了一些索引,但仍然在與我的id列中的值相同的那些數組索引處獲得了具有四個正確值的14個值。所以我真的認爲這是我的問題所在。你能否再詳細說明一下,我並不完全理解你的意思。非常感謝! – Wolfram 2009-05-26 18:21:22

3

答案在於@IndexColumn註釋。它使用id的值作爲數組索引,因此Array中元素的數量基本上是Authorities表中最高ID的值。

看到hibernate documentation on indexed collections

嘗試刪除註釋。

也只是作爲一個想法;你有沒有考慮過使用Set來進行映射?這不是絕對必要的,它只是一種更常見的映射形式。

+0

起初,我沒有@IndexColumn註解,導致「org.hibernate.AnnotationException:List/array必須用@IndexColumn註釋」。 至於類型問題:我正在實現「UserDetails」接口及其方法「GrantedAuthority [] getAuthorities();」。我會研究它來擺脫@IndexColumn。 你真的幫我理解了這個問題。 – Wolfram 2009-05-26 21:18:37