2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.usermgt.jpa;
18 import java.util.List;
20 import java.util.TreeSet;
22 import javax.persistence.EntityManager;
23 import javax.persistence.TypedQuery;
25 import org.wamblee.persistence.JpaMergeSupport;
26 import org.wamblee.usermgt.Group;
27 import org.wamblee.usermgt.GroupSet;
30 * Group set backed by the database.
32 * @author Erik Brakkee
34 public class JpaGroupSet implements GroupSet {
36 private EntityManager em;
38 public JpaGroupSet(EntityManager aEm) {
43 public boolean add(Group aGroup) {
44 assert aGroup.getPrimaryKey() == null;
45 if (contains(aGroup)) {
53 public boolean contains(Group aGroup) {
54 return find(aGroup.getName()) != null;
58 public Group find(String aName) {
59 TypedQuery<Group> query = em.createNamedQuery(Group.QUERY_FIND_BY_NAME,
61 query.setParameter(Group.NAME_PARAM, aName);
62 List<Group> groups = query.getResultList();
63 if (groups.size() > 1) {
64 throw new RuntimeException(
65 "More than one group with the same name '" + aName + "'");
68 if (groups.size() == 0) {
75 public void groupModified(Group aGroup) {
76 assert aGroup.getPrimaryKey() != null;
77 Group merged = em.merge(aGroup);
78 // Need to flush so that version of the merged instance is updated so we
80 // the updated version in the original group passed in. That allows the
82 // group object to continue to be used as a detached object.
84 JpaMergeSupport.merge(merged, aGroup);
88 public Set<Group> list() {
89 List<Group> groups = em.createNamedQuery(Group.QUERY_ALL_GROUPS,
90 Group.class).getResultList();
91 Set<Group> res = new TreeSet<Group>(groups);
96 public boolean remove(Group aGroup) {
97 Group group = find(aGroup.getName());
107 Long res = (Long) em.createNamedQuery(Group.QUERY_COUNT_GROUPS)
109 return res.intValue();