[编辑:显然,这只是数组的问题,Foxyboa的答案可能直接指向(甚至是)答案。]
我的问题与这些软件有关:hibernate3+注释、spring mvc、mysql,在这个例子中还有spring security。
我想知道,为什么hibernate自动关联的集合对于子表的每个行号都包含空值(除了正确的元素之外)。我的例子:
我有一个users和一个authorities表,users表的主键是充当外键的username。现在,我的authorities表中有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)个元素的集合“authorities”,其中只有4个元素不为空(数据库表中的4行属于该特定用户,所以这是正确的)。据我所知,我正在对fetchmode等属性使用hibernate默认值。
Criteria criteria = getSession().createCriteria(User.class);
criteria.add(Restrictions.eq("username",username));
User user = (User) criteria.uniqueResult();

org.hibernate.loader.loader中的日志信息正确地“提到”了resultset的四行。但是,用户创建的数组中有四个正确的元素加上十个空值。在我的特定示例中,这会导致以下异常:
java.lang.IllegalArgumentException: Granted authority element 0 is null - GrantedAuthority[] cannot contain any null elements

最佳答案

我建议你检查一下你的数据。如果您有一个丢失的索引(在您的例子中是id列),那么您将在数组中得到null而不是丢失的id。
即。

table authorities:
username id
bob 1
bob 3
bob 5

因此,您将拥有一个数组:
{0=null,1=bob,2=null,3=bob,4=null,5=bob}
更新:
我遇到了两种情况:
在authorities表中索引列id中缺少键值(例如0,1,3,4,5-缺少值2。hibernate将自动添加到键为2、值为空的数组值中。
索引值是按顺序排列的,但选择条件会过滤其中的一部分(例如,您的hql类似于“from user u join u.authorities a where a.id=2”。在这种情况下,hibernate加载用户,但在authorities数组中,只有3个值:0-null、1-null、2-authority(id为2)。

关于mysql - 为什么关联集合包含空值? (Hibernate,Annotation,Spring),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/910551/

10-09 06:19
查看更多