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, Group.class);
40 query.setParameter(Group.NAME_PARAM, aName);
41 List<Group> groups = query.getResultList();
42 if (groups.size() > 1) {
43 throw new RuntimeException(
44 "More than one group with the same name '" + aName + "'");
47 if (groups.size() == 0) {
54 public void groupModified(Group aGroup) {
55 assert aGroup.getPrimaryKey() != null;
56 Group merged = em.merge(aGroup);
57 // Need to flush so that version of the merged instance is updated so we can use
58 // the updated version in the original group passed in. That allows the same
59 // group object to continue to be used as a detached object.
61 JpaMergeSupport.merge(merged, aGroup);
65 public Set<Group> list() {
66 List<Group> groups = em.createNamedQuery(Group.QUERY_ALL_GROUPS, Group.class).getResultList();
67 Set<Group> res = new TreeSet<Group>(groups);
72 public boolean remove(Group aGroup) {
73 Group group = find(aGroup.getName());
74 if ( group == null ) {
83 Long res = (Long)em.createNamedQuery(Group.QUERY_COUNT_GROUPS).getSingleResult();
84 return res.intValue();