View Javadoc
1   /*
2    * JBoss, Home of Professional Open Source
3    * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
4    * contributors by the @authors tag. See the copyright.txt in the
5    * distribution for a full listing of individual contributors.
6    *
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * http://www.apache.org/licenses/LICENSE-2.0
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.jboss.as.quickstarts.kitchensink_ear.data;
18  
19  import javax.enterprise.context.ApplicationScoped;
20  import javax.inject.Inject;
21  import javax.persistence.EntityManager;
22  import javax.persistence.criteria.CriteriaBuilder;
23  import javax.persistence.criteria.CriteriaQuery;
24  import javax.persistence.criteria.Root;
25  import java.util.List;
26  
27  import org.jboss.as.quickstarts.kitchensink_ear.model.Member;
28  
29  @ApplicationScoped
30  public class MemberRepository {
31  
32      @Inject
33      private EntityManager em;
34  
35      public Member findById(Long id) {
36          return em.find(Member.class, id);
37      }
38  
39      public Member findByEmail(String email) {
40          CriteriaBuilder cb = em.getCriteriaBuilder();
41          CriteriaQuery<Member> criteria = cb.createQuery(Member.class);
42          Root<Member> member = criteria.from(Member.class);
43          // Swap criteria statements if you would like to try out type-safe criteria queries, a new
44          // feature in JPA 2.0
45          // criteria.select(member).where(cb.equal(member.get(Member_.email), email));
46          criteria.select(member).where(cb.equal(member.get("email"), email));
47          return em.createQuery(criteria).getSingleResult();
48      }
49  
50      public List<Member> findAllOrderedByName() {
51          CriteriaBuilder cb = em.getCriteriaBuilder();
52          CriteriaQuery<Member> criteria = cb.createQuery(Member.class);
53          Root<Member> member = criteria.from(Member.class);
54          // Swap criteria statements if you would like to try out type-safe criteria queries, a new
55          // feature in JPA 2.0
56          // criteria.select(member).orderBy(cb.asc(member.get(Member_.name)));
57          criteria.select(member).orderBy(cb.asc(member.get("name")));
58          return em.createQuery(criteria).getResultList();
59      }
60  }