20

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

Ben
  • 60,438
  • 111
  • 314
  • 488
sandeep
  • 227
  • 2
  • 6
  • 9

4 Answers4

38

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();
Dick Chesterwood
  • 2,629
  • 2
  • 25
  • 33
4

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

brent777
  • 3,369
  • 1
  • 26
  • 35
2

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.

OpenSource
  • 2,217
  • 2
  • 21
  • 22
1

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

Reza P.
  • 306
  • 2
  • 18