我有两个具有单向惰性关系的实体。其中一个有一个命名实体图。以下是实体(由于可读性而未列出getter和setter):
@Entity
@NamedEntityGraph (
name = "Sms.fetchSims",
attributeNodes = {
@NamedAttributeNode("sim")
}
)
public class Sms {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private Long id;
@NotNull
private Timestamp date;
@NotNull
private String sender;
@NotNull
private String content;
@NotNull
private Direction direction;
@NotNull
@ManyToOne (fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private Sim sim;
}
@Entity
public class Sim {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private long id;
@NotNull
private long IMSI;
private String MSISDN;
private String provider;
private Timestamp lockedDate;
}
当我使用带有此实体图的实体管理器find()方法获取任何短信时,我得到一个带有sim的短信。 但我希望能够通过sim id找到微笑。这就是为什么我为此目的创建了一个标准api查询。
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
EntityGraph eg = entityManager.getEntityGraph("Sms.fetchSims");
CriteriaQuery<Sms> cq = cb.createQuery(Sms.class);
Root<Sms> smses = cq.from(Sms.class);
Join<Sms, Sim> sims = smses.join(Sms_.sim);
cq.where(cb.equal(sims.get(Sim_.id), simId));
cq.orderBy(cb.desc(smses.get(Sms_.date)));
return entityManager
.createQuery(cq)
.setHint("javax.persistence.fetchgraph", eg)
.setMaxResults(1000)
.getResultList();
如你所见,我在这里使用类型化查询的setHint方法设置实体图,但是从不提取sim,它的字段甚至没有在结果sql中列出。如何使实体图使用标准api?
我知道我可以将smses.fetch(Sms_.sim)强制转换为Join,但是我收到了丑陋的警告,这个方法对我来说就像是一个肮脏的黑客。
我正在使用hibernate和wildfly-8.2.0.Final应用服务器。
答案 0 :(得分:1)
DEBUG - org.hibernate.SQL -
select
sms0_.id as id1_1_0_,
sim1_.id as id1_0_1_,
sms0_.content as content2_1_0_,
sms0_.date as date3_1_0_,
sms0_.direction as directio4_1_0_,
sms0_.sender as sender5_1_0_,
sms0_.sim_id as sim_id6_1_0_,
sim1_.IMSI as IMSI2_0_1_,
sim1_.MSISDN as MSISDN3_0_1_,
sim1_.lockedDate as lockedDa4_0_1_,
sim1_.provider as provider5_0_1_
from
Sms sms0_
inner join
Sim sim1_
on sms0_.sim_id=sim1_.id
where
sim1_.id=1
order by
sms0_.date desc limit ?
这里是4.3.8查询:
DEBUG - org.hibernate.SQL -
select
sms0_.id as id1_1_,
sms0_.content as content2_1_,
sms0_.date as date3_1_,
sms0_.direction as directio4_1_,
sms0_.sender as sender5_1_,
sms0_.sim_id as sim_id6_1_
from
Sms sms0_
inner join
Sim sim1_
on sms0_.sim_id=sim1_.id
where
sim1_.id=1
order by
sms0_.date desc limit ?