JPA连接具有空值的列

时间:2009-11-03 14:31:45

标签: java orm join null

我有一个在纯SQL中工作的查询,但是没有在JPA上工作,也无法找出原因。你可以从标题中猜出我有一个线索,但我不知道如何“修复”它。

这是实际的重要代码:

@Id 
@Basic(optional = false) 
@Column(name = "id", nullable = false) 
private Integer id; 

@Basic(optional = false) 
@Column(name = "read_permission", nullable = false) 
private boolean readPermission; 

@Basic(optional = false) 
@Column(name = "write_permission", nullable = false) 
private boolean writePermission; 

@Basic(optional = false) 
@Column(name = "execute_permission", nullable = false) 
private boolean executePermission; 

@Basic(optional = false) 
@Column(name = "admin_permission", nullable = false) 
private boolean adminPermission; 

@JoinColumn(name = "xinco_core_data_id", referencedColumnName = "id", nullable=true) 
@ManyToOne(fetch = FetchType.LAZY) 
private XincoCoreData xincoCoreDataId; 
@JoinColumn(name = "xinco_core_group_id", referencedColumnName = "id", nullable=true) 
@ManyToOne(fetch = FetchType.LAZY) 
private XincoCoreGroup xincoCoreGroupId; 

@JoinColumn(name = "xinco_core_node_id", referencedColumnName = "id", nullable=true) 
@ManyToOne(fetch = FetchType.LAZY) 
private XincoCoreNode xincoCoreNodeId; 

@JoinColumn(name = "xinco_core_user_id", referencedColumnName = "id", nullable=true) 
@ManyToOne(fetch = FetchType.LAZY) 
private XincoCoreUser xincoCoreUserId; 

这是工作的sql:

select * from xinco_core_ace where xinco_core_user_id = 1 order by xinco_core_user_id, xinco_core_node_id, xinco_core_data_id; 

这就是我要做的事情:

SELECT xca FROM XincoCoreAce xca WHERE xca.xincoCoreUserId.id = 1 ORDER BY xca.xincoCoreUserId.id, xca.xincoCoreGroupId.id, xca.xincoCoreNodeId.id, xca.xincoCoreDataId.id

我认为,问题是xca.xincoCoreUserId.id,xca.xincoCoreGroupId.id,xca.xincoCoreNodeId.id,xca.xincoCoreDataId.id可以为空。

有什么想法吗?希望更容易阅读:P

3 个答案:

答案 0 :(得分:2)

我也遇到了一个更简单的问题:

select t from Task t where t.worker is not null order by t.worker.normalizedName

发现属性worker为null(任务未分配)的任何任务结果实体都将被丢弃。后来我发现这是因为JPA中的路径导航是使用内部连接完成的(规范是这样说的),这将排除路径的一部分为空的任何结果。

此错误报告准确描述了问题:

https://bugs.eclipse.org/bugs/show_bug.cgi?id=363798

不幸的是,这不是实施错误,您必须重构您的实体/查询以避免这种情况。

答案 1 :(得分:1)

这是完成的实际查询(使用eclipselink日志记录):

SELECT t1.id, t1.write_permission, t1.admin_permission, t1.execute_permission, t1.read_permission, t1.xinco_core_user_id, t1.xinco_core_data_id, t1.xinco_core_group_id, t1.xinco_core_node_id FROM xinco_core_data t4, xinco_core_node t3, xinco_core_group t2, xinco_core_ace t1, xinco_core_user t0 WHERE ((t3.id = ?) AND ((((t3.id = t1.xinco_core_node_id) AND (t0.id = t1.xinco_core_user_id)) AND (t2.id = t1.xinco_core_group_id)) AND (t4.id = t1.xinco_core_data_id))) ORDER BY t0.id ASC, t2.id ASC, t3.id ASC, t4.id ASC bind => [1]

由于某些原因,使用Order by添加了大量的表交叉检查,其中有空值会使结果变空。

删除订单会获得所需的结果(当然不按顺序)。

请参阅此Eclipselink bug

答案 2 :(得分:0)

我这里不是JPA专家,但我会尝试获取在数据库上运行的实际SQL。也许FetchType.LAZY与问题有关?