1
2
3
4
5
6
7 package ch.colabproject.colab.api.persistence.jpa.user;
8
9 import ch.colabproject.colab.api.exceptions.ColabMergeException;
10 import ch.colabproject.colab.api.model.user.User;
11 import java.util.List;
12 import javax.ejb.LocalBean;
13 import javax.ejb.Stateless;
14 import javax.persistence.EntityManager;
15 import javax.persistence.NoResultException;
16 import javax.persistence.PersistenceContext;
17 import javax.persistence.TypedQuery;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21
22
23
24
25
26
27
28 @Stateless
29 @LocalBean
30 public class UserDao {
31
32
33 private static final Logger logger = LoggerFactory.getLogger(UserDao.class);
34
35
36
37
38 @PersistenceContext(unitName = "COLAB_PU")
39 private EntityManager em;
40
41
42
43
44
45
46
47
48 public User findUser(Long id) {
49 logger.trace("find user #{}", id);
50
51 return em.find(User.class, id);
52 }
53
54
55
56
57
58
59 public List<User> findAllUsers() {
60 logger.trace("find all users");
61
62 TypedQuery<User> query = em.createNamedQuery("User.findAll", User.class);
63
64 return query.getResultList();
65 }
66
67
68
69
70
71
72 public List<User> findAllAdmin() {
73 logger.trace("find all admin users");
74
75 TypedQuery<User> query = em.createNamedQuery("User.findAllAdmin", User.class);
76
77 return query.getResultList();
78 }
79
80
81
82
83
84
85
86
87 public User findUserByUsername(String username) {
88 logger.trace("find user with username {}", username);
89 try {
90 TypedQuery<User> query = em.createNamedQuery("User.findByUsername", User.class);
91
92 query.setParameter("username", username);
93
94 return query.getSingleResult();
95 } catch (NoResultException ex) {
96 return null;
97 }
98 }
99
100
101
102
103
104
105
106
107
108
109 public User updateUser(User user) throws ColabMergeException {
110 logger.trace("update user {}", user);
111
112 User managedUser = this.findUser(user.getId());
113
114 managedUser.mergeToUpdate(user);
115
116 return managedUser;
117 }
118
119
120
121
122
123
124
125
126 public User persistUser(User user) {
127 logger.trace("persist user {}", user);
128
129 em.persist(user);
130
131 return user;
132 }
133
134 }