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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top