我正在使用播放框架和 JPA 和 Hibernate。
我有几个实体:
@Entity
public class Player extends Model {
public enum Gender {
MALE, FEMALE
}
@Required
public String name;
@Required
public Gender gender;
@Required
public Long gold;
}
@Entity
public class Building extends Model {
@Required
@ManyToOne(fetch = FetchType.LAZY)
public Player owner;
@Required
public String buildingType;
@Required
public Long buildingId;
}
@Entity
public class Stock extends Model {
// Either a product type or a raw material
@Required
public Long goodId;
@Required
public Boolean isProduct;
@Required
public String image;
}
@Entity
public class Contract extends Model {
@Required
@ManyToOne(fetch = FetchType.LAZY)
public Player player;
@Required
@ManyToOne(fetch = FetchType.LAZY)
public Building building;
@Required
@ManyToOne(fetch = FetchType.LAZY)
public Stock stock;
@Required
public Long ordersLeft;
@Required
public Long cyclesLeft;
}
有了这些实体,我想检索所有我的Contract和他们相关的Building,Stock和Player
这是我使用的查询:
public static List<Contract> retrieveContractsForNewOrder() {
return find("select distinct c from Contract c "
+ "left join fetch c.player "
+ "left join fetch c.stock "
+ "left join fetch c.building "
+ "where c.cyclesLeft = 0 and c.ordersLeft > 0").fetch();
}
查询正在运行,我检索了我的Contract. 但是,building和stock变量已加载但player变量未加载(对象中的类名Contract是Player_$$_javassist_22并且它有一个名为 的处理程序JavassistLazyInitializer)。
我不知道我做错了什么以及为什么 Hibernate 在获取其他模型时拒绝获取玩家模型......
感谢您的帮助
编辑
经过一些测试,hibernate 执行的查询似乎是正确的:所有连接都在那里,所有模型的所有字段都在选择中。
但是结果很奇怪:我只是从Contractand Stock(不是从Buildingand Player)检索字段。
但是我Building的已经加载了,为什么?因为缓存?为什么Building并Player没有出现在结果中?
编辑 2
我试图直接在 MySQL 中执行完全相同的请求,并且我正在检索我需要的所有变量,而 Hibernate 似乎跳过了一些变量(它们并不全部在结果中)。
发生了什么 ?
编辑 3
clear()我在进行查询之前尝试了会话缓存,你猜怎么着?已Player加载...
我尝试只加载Playerusing ,left join fetch但它仍然无法正常工作(但Building由于缓存而被加载)。Player's字段不在结果中。但是,一旦我清除缓存,Player's字段就会出现在结果中,并且Player会加载到我的Contract.
为什么清除缓存解决了这个问题?Player在缓存中?如果是这样,为什么它没有加载?我不明白会发生什么,但我不能只清除缓存,因为我需要在此之后进行很多其他查询,并且我需要它们的缓存。