hibernate - 如何为 OneToOne 生成 hql 查询

标签 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 查询的新手,所以这是我尝试过的:

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

关于hibernate - 如何为 OneToOne 生成 hql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50803183/

相关文章:

java - 在 Java 持久性中较旧的查询

java - HQL 查询在运行 SQL 查询时抛出 QueryException

java - org.postgresql.util.PGobject 无法转换为 org.postgis.PGgeometry

java - Hibernate Criteria 唯一结果(键以外的列)

java - 警告 : java. lang.IndexOutOfBoundsException

java - 如何在 hibernate 中获取排序结果中的第一组结果?

hibernate - HQL:从日期减去天数以获取新日期

java - 具有两个抽象类的 JPA 继承

java - JPQL,有没有一种方法可以过滤子集合,而不同时过滤不满足条件的父集合?

java - 如何强制 hibernate 以不同模式搜索值?