如何为OneToOne生成hql查询

时间:2018-06-11 17:29:50

标签: hibernate hql

我有品牌类,它被映射为规范类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 Query的新手,所以我尝试了这个:

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?

1 个答案:

答案 0 :(得分: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