简体   繁体   中英

How I get a @NamedQuery Query with WERE Command in Java EE?

hi i have a java ee application and I want to create a Query to get all Tickets from a User.

I have a Ticket class, TicketDAO Interface and TicketBean class I have a User class, UserDAO interface and UserBean class

Here is my User class:

  @Entity
    @NamedQueries({
        @NamedQuery(name=User.QUERY_GETALL,query="SELECT c FROM User c"),
        @NamedQuery(name=User.QUERY_GETALLTICKETS,query="SELECT c FROM Ticket c ...????"),
    })
    public class User implements Serializable{

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public static final String QUERY_GETALL = "User.GetAll";

        public static final String QUERY_GETALLTICKETS = "User.GetAllTickets";
...

here is my UserBean class:

@Override
public List<Ticket> getAllUserTickets() {

    return em.createNamedQuery(User.QUERY_GETALLTICKETS,Ticket.class).getResultList();
}

My Ticket Table have the column username.

Move QUERY_GETALLTICKETS from the User class to the Ticket class; then you can write something like:

@NamedQuery(name=Ticket.QUERY_GETALLTICKETS,query="SELECT t FROM Ticket t where t.userName = :" + P_USER)

Declare P_USER as:

public final static String P_USER = "pUser";

Then you can use the query this way:

@Override public List getAllUserTickets(String username) {

Query query = em.createNamedQuery(Ticket.QUERY_GETALLTICKETS,Ticket.class); query.setParameter(Ticket.P_USER, username);

return query.getResultList(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM