有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate从HQL生成错误的SQL

我正在尝试使用以下HQL查询连接两个表,用户和托管平台。托管平台表对用户表有一个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。平台id,但Hibernate正在用户0上运行。id=hostingpla1。身份证

主机平台。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) 个答案

  1. # 1 楼答案

    我在HostingPlatform的“平台”字段中缺少@manytone注释。JAVA 添加批注后问题已解决

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