Hibernate从HQL生成错误的SQL

时间:2016-09-07 09:08:11

标签: java hibernate

我正在尝试使用以下HQL查询加入2个表,user和hosting_platform。 hosting_platform表具有对用户表的FK引用。 数据库是postgresql。

select u.id, u.userName, p.platform.id, p.itemPrice, p.revenueShare 
from User u left join HostingPlatform p on u.id = p.platform.id AND
p.item.id = :itemId where u.userType = 'Platform'

我没有从上面的查询得到预期的结果,因为hibernate没有从上面的HQL生成正确的SQL查询。 以下普通SQL由Hibernate生成。

select
        user0_.id as col_0_0_,
        user0_.user_name as col_1_0_,
        hostingpla1_.id as col_2_0_,
        hostingpla1_.item_price as col_3_0_,
        hostingpla1_.revenue_share as col_4_0_ 
    from
        users user0_ 
    left outer join
        user_role user0_1_ 
            on user0_.id=user0_1_.user_id 
    left outer join
        hosting_platform hostingpla1_ 
            on (
                user0_.id=hostingpla1_.id 
                and hostingpla1_.item_id=?
            ) 
    where
        user0_.user_type='Platform' 

基于我的HQL连接应该发生在user0_.id = hostingpla1_.platform_id上,但Hibernate正在user0_.id = hostingpla1_.id上进行。

HostingPlatform.java定义为

@Entity  
@Table(name="hosting_platform")
public class HostingPlatform {
private static final long serialVersionUID = 6311364761937265306L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hosting_platform_id_seq")
    @SequenceGenerator(name = "hosting_platform_id_seq", sequenceName = "hosting_platform_id_seq", allocationSize=1)
    @Column(name = "id")
    private Long id;

    @JoinColumn(name = "platform_id")
    private User platform;

    @ManyToOne
    @JoinColumn(name="item_id")
    private Item item;

    @Column(name = "item_price")
    private Double itemPrice;

    @Column(name = "revenue_share")
    private Double revenueShare;
}

谢谢。

1 个答案:

答案 0 :(得分:0)

我在'平台'上错过了@ManyToOne注释。 HostingPlatform.java中的字段。 添加注释后问题已解决

@ManyToOne
@JoinColumn(name = "platform_id")
private User platform;