我遇到一个问题,其中Hibernate(4.1.8.FINAL)返回带有NULL值的列表(单向OneToMany映射)。
我得到的是: 我得到一个大小为21的列表,其中EntryAddress在第10个索引上,而2nd Entry Address在第20个索引上。
Entry [addresses=[null, null, null, null, null, null, null, null, null, null, EntryAddress [id=5, entryId=3, precedence=10, line=Line 3.1], null, null, null, null, null, null, null, null, null, EntryAddress [id=6, entryId=3, precedence=20, line=Line 3.2]]]
我所期望的 -我期望一个只有两个EntryAddress对象的List:
Entry [addresses=[EntryAddress [id=5, entryId=3, precedence=10, line=Line 3.1], EntryAddress [id=6, entryId=3, precedence=20, line=Line 3.2]]]
这是最小的源代码:
@Entity @Table(name = "entry") public class Entry { ... @OneToMany(fetch = FetchType.EAGER, orphanRemoval = true) @JoinColumn(name = "entry_id") @OrderColumn(name = "precedence") private List<EntryAddress> addresses; ... } @Entity @Table(name = "entry_address") public class EntryAddress { @Id @GeneratedValue @Column(name = "id") private Integer id; @Column(name = "entry_id") private Integer entryId; @Column(name = "precedence") private Integer precedence; ... }
这是mysql结构(InnoDB引擎):
CREATE TABLE entry ( id int(10) unsigned NOT NULL AUTO_INCREMENT, name varchar(500) NOT NULL, active int(1) NOT NULL DEFAULT '0', modifiedTS timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP, createdTS timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY ( id ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- CREATE TABLE entry_address ( id int(10) unsigned NOT NULL AUTO_INCREMENT, entry_id int(10) unsigned NULL, precedence int(2) NULL DEFAULT '0', line varchar(255) DEFAULT NULL, PRIMARY KEY ( id ), UNIQUE KEY entry_address_uq ( entry_id , precedence ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
当我尝试用“设置”替换“列表”时,集合没有NULL值,但是序列/优先级不起作用。
我发现的一个有趣的问题是,如果我将1st EntryAddress的优先级设置为1,并将2nd EntryAddress的优先级设置为2,那么我将得到一个大小为2的列表。因此,尽管在返回List的过程中,优先级似乎起着一定的作用优先级仅应用于排序。
你能告诉我我做错了吗?谢谢 :-)
我找到了解决方案,我用了它,这解决了问题
@OneToMany(orphanRemoval = true) @LazyCollection(LazyCollectionOption.FALSE) @JoinColumn(name = "entry_id") @OrderBy("precedence") private List<EntryAddress> addresses; @OneToMany(orphanRemoval = true) @LazyCollection(LazyCollectionOption.FALSE) @JoinColumn(name = "entry_id") @OrderBy("precedence") private List<EntryContact> contacts;