sandeep
sandeep

Reputation: 227

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

Upvotes: 20

Views: 44325

Answers (4)

Reza P.
Reza P.

Reputation: 306

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

Upvotes: 1

brent777
brent777

Reputation: 3379

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 ":")

Upvotes: 4

OpenSource
OpenSource

Reputation: 2257

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.

Upvotes: 2

Dick Chesterwood
Dick Chesterwood

Reputation: 2659

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();

Upvotes: 38

Related Questions