-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathGenericDAO.java
More file actions
63 lines (50 loc) · 1.51 KB
/
GenericDAO.java
File metadata and controls
63 lines (50 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.stefanini.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.transaction.Transactional;
import java.lang.reflect.ParameterizedType;
import java.util.List;
public class GenericDAO<T, I> {
@PersistenceContext(unitName = "PU")
EntityManager em;
Class<T> clazz;
public GenericDAO() {
clazz = ((Class) ((ParameterizedType) getClass().getSuperclass().getGenericSuperclass()).getActualTypeArguments()[0]);
}
@Transactional
public T save(T t){
em.persist(t);
return t;
}
public T findById(I id){
return em.find(clazz, id);
}
public List<T> listAll(){
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<T> query = builder.createQuery(clazz);
query.from(clazz);
return em.createQuery(query).getResultList();
}
@Transactional
public T update(T t){
return em.merge(t);
}
@Transactional
public void delete(I id){
T t = findById(id);
em.remove(t);
}
public TypedQuery<T> createQuery(String query) {
return em.createQuery(query, clazz);
}
public Query createNativeQuery(String query) {
return em.createNativeQuery(query, clazz);
}
public EntityManager getEntityManager() {
return em;
}
}