我有品牌类,它与规范类 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/