【问题标题】:how to generate hql query for OneToOne如何为 OneToOne 生成 hql 查询
【发布时间】:2018-06-20 01:39:50
【问题描述】:

我有品牌类,它与规范类MobileBrands.class 一对一映射:

private int id;
private String name;
private int price;
@OneToOne
private MobileSpecification prodInfo;

MobileSpecification.class:

private int id;
private String ram;
private String rom;
@OneToOne
private MobileBrands brands;

我知道 sql 可以正常工作。

SQL:

select mobile_brands.id, mobile_brands.name, specification.ram, specification.rom 
        from mobile_brands inner join specification on 
            mobile_brands.brand_id=specification.ID where mobile_brands.BRAND_ID='1'

虽然我是 HQL 查询的新手,但我已经尝试过:

SELECT u.id as id, u.name as name, 
    u.prodInfo.ram as ram, u.prodInfo.rom as rom from MobileBrands inner join MobileSpecification 
        with MobileBrands.id=MobileSpecification.id where MobileBrands.id='1'"

哪个不起作用(HQL 之一)。怎么转成HQL?

【问题讨论】:

    标签: hibernate hql


    【解决方案1】:

    更改自:

    SELECT u.id as id, u.name as name, 
    u.prodInfo.ram as ram, u.prodInfo.rom as rom from MobileBrands inner join MobileSpecification 
        with MobileBrands.id=MobileSpecification.id where MobileBrands.id='1'"
    

    收件人:

    select new com.package.app.MobileDto(mb.id, md.name, ms.rom, ms.ram) FROM MobileBrands mb, MobileSpecification ms WHERE mb.id = 1 and mb.id = ms.id
    

    如您所见,我正在使用 MbDto 类来接收每个信息。您可以使用字段的构造函数在包(每个示例)com.package.app 上创建此类:

    class MbDto {
    
        MbDto(int id, String name, String ram, String rom) {
             // constructor will all fields
        }
    }
    

    如果您只期望一个结果(示例),请使用它:

    String jpql = "select new com.package.app.MobileDto(mb.id, md.name, ms.rom, ms.ram) FROM MobileBrands mb, MobileSpecification ms WHERE mb.id = 1 and mb.id = ms.id";
    Query query = entityManager.createQuery(jpql);
    MbDto mbDto = query.getSingleResult();
    

    较新版本的 Hibernate 可以在没有关系的情况下进行 JOIN,但这不是您的问题所必需的。

    但请注意,您没有使用这两个实体之间的映射关系。如果您尝试这样做,查询将是:

    select mb FROM MobileBrands mb JOIN mb.productInfo pi WHERE mb.id = 1
    

    【讨论】:

    • 虽然我没有尝试过你的方法,但我的要求是我需要一些来自 MobileBrands 的特定属性,并且它与 MobileSpecifiaction 类相关联。就像我的 MobileBrands 和 MobileSpecification 包含许多属性,但我从 MobileBrands 和 MobileSpecification 中找到了一些 selected 属性。我认为这种方法将提供整个类属性,但我不想通过选择特定属性来减少查询生成
    • 这也是可能的。您可以选择属性并使用Dto 来获取这些值。我会将其添加到我的答案中
    • @RiaMohanty 再次看到我的答案
    猜你喜欢
    • 2012-02-06
    • 2021-01-31
    • 2021-11-02
    • 1970-01-01
    • 2017-10-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多