1 package org.wamblee.usermgt.jpa;
5 import java.util.TreeSet;
7 import javax.persistence.EntityManager;
8 import javax.persistence.TypedQuery;
10 import org.wamblee.persistence.JpaMergeSupport;
11 import org.wamblee.usermgt.Group;
12 import org.wamblee.usermgt.GroupSet;
14 public class JpaGroupSet implements GroupSet {
16 private EntityManager em;
18 public JpaGroupSet(EntityManager aEm) {
23 public boolean add(Group aGroup) {
24 assert aGroup.getPrimaryKey() == null;
25 if (contains(aGroup)) {
33 public boolean contains(Group aGroup) {
34 return find(aGroup.getName()) != null;
38 public Group find(String aName) {
39 TypedQuery<Group> query = em.createNamedQuery(Group.QUERY_FIND_BY_NAME,
41 query.setParameter(Group.NAME_PARAM, aName);
42 List<Group> groups = query.getResultList();
43 if (groups.size() > 1) {
44 throw new RuntimeException(
45 "More than one group with the same name '" + aName + "'");
48 if (groups.size() == 0) {
55 public void groupModified(Group aGroup) {
56 assert aGroup.getPrimaryKey() != null;
57 Group merged = em.merge(aGroup);
58 // Need to flush so that version of the merged instance is updated so we
60 // the updated version in the original group passed in. That allows the
62 // group object to continue to be used as a detached object.
64 JpaMergeSupport.merge(merged, aGroup);
68 public Set<Group> list() {
69 List<Group> groups = em.createNamedQuery(Group.QUERY_ALL_GROUPS,
70 Group.class).getResultList();
71 Set<Group> res = new TreeSet<Group>(groups);
76 public boolean remove(Group aGroup) {
77 Group group = find(aGroup.getName());
87 Long res = (Long) em.createNamedQuery(Group.QUERY_COUNT_GROUPS)
89 return res.intValue();