如何为 OneToOne 生成 hql 查询

how to generate hql query for OneToOne

我有品牌 class 与规格 class 映射为一对一 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?

更改自:

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 class 来接收每条信息。您可以在包上创建此 class(每个示例)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