Named query when property is an object?

隐身守侯 提交于 2019-12-10 22:38:23

问题


I would like to make this query in JPA:

SELECT * FROM `happyDB`.`users` U WHERE U.party_as_user =1 AND U.party_party_id =2

This is working fine, but my problem is that I have Party only as an object, not as an id and I can't make it work.

In the Users-entity where I am trying to do the named query I have the following:

@JoinColumn(name = "pary_party_id", referencedColumnName = "party_id")
@ManyToOne
private Party partyId;

@Column(name = "party_as_user")
private Boolean partyAsUser;

I tried to implement it like an object with dot notation, but that's not working:

@NamedQuery(name = "Users.findByPartyAsUser", query = "SELECT u FROM Users u WHERE u.partyAsUser = :partyAsUser AND u.partyId.partyId = :partyId")

There is a property called partyId inside the Party-object, but it's not working. Is there any solution for that or do I have to add one property to the Users-bean like private int partyID and populate it every time when a new Party is inserted into Users?

Thanks for helping! Sami Nurmi


回答1:


In general you can use an object as a parameter in JPA,

SELECT u FROM Users u WHERE u.partyAsUser = :partyAsUser AND u.party  = :party

Party party = new Party(id);
query.setParameter("party", party);

But what you have should work if you use the correct variable names, my guess is,

SELECT u FROM Users u WHERE u.partyAsUser = :partyAsUser AND u.party.id  = :id

And you can always use a native SQL query, if you understand SQL better than objects.



来源:https://stackoverflow.com/questions/10158255/named-query-when-property-is-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!