What's the right HQL Syntax for this query?
I have a class GameDefinition
that extends ItemDefinition
.
I also have other classes that extend ItemDefinition
.
I have another class StoreItem
that has an attribute named itemDefinition
of type ItemDefinition
.
I want to find all GameDefinitions
joined to their StoreItems
. But of course, I don't want to get other definitions that extend ItemDefinitio开发者_开发知识库n
.
In raw sql I would expect something like this to work.
select * from game_definition g
inner join store_item s on g.id=s.item_definition_id
What is the proper HQL
way for this?
It's not about the HQL so much as configuring the mapping in the entity bean. Assuming GameDefinition
is an @Entity
, something like this:
SELECT g FROM GameDefinition g
You'd configure the actual StoreItems
with some sort of mapping (one-to-one, one-to-many, etc.) using the appropriate annotation. If, for example, the mapping was one-to-one:
GameDefinition.java
@Entity
@Table(name="game_definition")
public class GameDefinition implements Serializable
{
// snip other fields...
private StoreItem storeItem;
// snip other getters/setters...
@Fetch(FetchMode.JOIN)
@OneToOne(fetch = FetchType.EAGER, mappedBy = "gameDefinition")
public StoreItem getStoreItem()
{
return storeItem;
}
public void setStoreItem(StoreItem storeItem)
{
this.storeItem = storeItem;
}
}
StoreItem.java
@Entity
@Table(name="store_item")
public class StoreItemimplements Serializable
{
// snip other fields...
private GameDefinition gameDefinition;
// snip other getters/setters...
@Fetch(FetchMode.JOIN)
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "item_definition_id")
public GameDefinition getGameDefinition()
{
return gameDefinition;
}
public void setGameDefinition(GameDefinition gameDefinition)
{
this.storeItem = gameDefinition;
}
}
Edit: you could actually do this with HQL, but then Query#getResultList()
would return a List<Object[]>
, which would require casting, and be ugly, etc. Let me know if you want to see how this would be done.
精彩评论