开发者

How to call Named Query

I wrote a named query in the entity class Voter

NamedQuery(name = "Voter.findvoter", query = "SELECT count(*) FROM Voter v WHERE v.voterID = :voterID" and where v.password= : password),

I want to call this named query and I also 开发者_开发百科need to set voterID and password.

Can you help me. Thank you


I assume you've missed the @ symbol on your NamedQuery annotation?

In the code, you'd call it like this:

List results = em.createNamedQuery("Voter.findvoter")
    .setParameter("voterID", "blah")
    .setParameter("password","blahblahblah")
    .getResultList();


There are two obvious issues with your named query that would cause a problems:

  • It is an annotation so it should be @NamedQuery not just NamedQuery
  • Your query is currently:

query = "SELECT count(*) FROM Voter v WHERE v.voterID = :voterID" and where v.password= : password.

The problem is that you terminate your String after :voterID, instead of after :password and you have "where" twice and you have a space between ":" and "password". Your query should look like this:

query = "SELECT count(*) FROM Voter v WHERE v.voterID = :voterID and v.password= :password"

(I have just moved the " to the end and removed the second "where" and the space after the ":")


The common steps are (named query or otherwise)

  1. Create a query - em has five create methods.
  2. Set the query up with parameters if needed - the query interface has these methods.
  3. Execute the query - the query interface has 3 execution related methods.

with the above three steps you can run any JPA query.


Actually brent is right your NameQuery should be something like this,

@NamedQuery(name = "Voter.findvoter", query = "SELECT count(*) FROM Voter v WHERE v.voterID = :voterID AND where v.password = :password")
@Entity
public class Voter implements Serializable{ ... }

and somewhere else you should try this one (which Dick has already said)

public class VoterFasade{
    public List<Voter> findVoter(long id,String password){
        List<Voter> results = em.createNamedQuery("Voter.findvoter")
            .setParameter("voterID", id)
            .setParameter("password",password)
            .getResultList();
        return result;
    }
}

then you could use it like

@Inject
VoterFasade voterFasade;

///
long id=12;
voterFasade.findVoter(id);

should actually working.(its an uncompiled code).

you could also do it with Repository, check the link below, part Repository Listing23.Example repository enter link description here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜