我有一个与Traveller
有关系的班级TravellerVote
。我希望找回旅行者的投票票数和收到的票数。
班级旅行者
@Entity
@PrimaryKeyJoinColumn(name="user_id")
public class Traveller extends User{
@OneToMany(mappedBy="voter", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
protected List<TravellerVote> myVotes;
@OneToMany(mappedBy="partner", cascade={CascadeType.PERSIST, CascadeType.REMOVE})
protected List<TravellerVote> receivedVotes;
public Traveller(){
super();
myVotes = new ArrayList<TravellerVote>();
receivedVotes = new ArrayList<TravellerVote>();
}
public void addVote(TravellerVote vote){
myVotes.add(vote);
}
}
Class TravellerVote
@Entity
public class TravellerVote {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(length=11)
protected long id;
@ManyToOne
@JoinColumn(name="voter_id")
protected Traveller voter;
@ManyToOne
@JoinColumn(name="partner_id")
protected Traveller partner;
@Column(nullable=false)
protected Date date;
@Column(length=300, nullable=true)
protected String comment;
@Column(nullable=false)
protected boolean positive;
public TravellerVote(Traveller voter, Traveller partner, String comment, boolean positive){
this.date = new Date();
this.voter = voter;
this.partner = partner;
this.comment = comment;
this.positive = positive;
}
}
实体在数据库中正确保留,其中包含:
TravellerDao dao = new TravellerDao();
Traveller t1 = dao.findByUsername("ramiromd");
Traveller t2 = dao.findByUsername("danimd");
Traveller t3 = dao.findByUsername("famartinezd");
t1.addVote(new TravellerVote(t1, t2, "Test comment", true));
t2.addVote(new TravellerVote(t2, t1, "Test comment", true));
t3.addVote(new TravellerVote(t3, t1, "Test comment", false));
dao.save(t1);
dao.save(t2);
dao.save(t3);
但是,当在其他控制器尝试获得投票时,集合有0个元素。
TravellerDao dao = new TravellerDao();
Traveller t1 = dao.findByUsername("ramiromd");
t1.getReceivedVotes().size(); // Must be 2 not 0.
t1.getMyVotes().size(); // Must be 1 not 0.
TravellerDao保存方法:
public void save(Traveller traveller) {
EntityManager em = PersistenceHelper.getEm();
em.getTransaction().begin();
em.persist(traveller);
//em.flush();
em.getTransaction().commit();
}
这是findByUsername方法:
public Traveller findByUsername(String username){
EntityManager em = PersistenceHelper.getEm();
String qstring = "SELECT t FROM Traveller t WHERE t.username LIKE :username";
TypedQuery<Traveller> query = em.createQuery(qstring, Traveller.class);
query.setParameter("username", username);
return query.getSingleResult();
}
有什么想法吗?
答案 0 :(得分:1)
在这些场景中,启用实现框架的调试很有帮助。例如,如果您正在使用Hibernate,请将org.hibernate包的调试级别设置为&#34; DEBUG&#34;。这将显示所有被触发的SQL。在您的问题中,如果将fetch设置为等于LAZY,您将看到针对这些语句触发的确切SQL: -
t1.getReceivedVotes().size(); // Must be 2 not 0.
t1.getMyVotes().size();
希望这会给你足够的提示来解决这个问题。
答案 1 :(得分:0)
我不知道你的dao save()方法是怎样的,但是有:
getEntityManager().flush();
如果没有,请在坚持后添加并检查是否有帮助。