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 package fr.paris.lutece.plugins.stock.commons.dao;
35
36 import fr.paris.lutece.plugins.stock.commons.ResultList;
37 import fr.paris.lutece.portal.service.jpa.JPALuteceDAO;
38
39 import javax.persistence.EntityManager;
40 import javax.persistence.Query;
41 import javax.persistence.criteria.CriteriaBuilder;
42 import javax.persistence.criteria.CriteriaQuery;
43 import javax.persistence.criteria.Expression;
44 import javax.persistence.criteria.Predicate;
45 import javax.persistence.criteria.Root;
46
47
48
49
50
51
52
53
54
55
56 public abstract class AbstractStockDAO<K, E> extends JPALuteceDAO<K, E>
57 {
58
59
60
61
62
63
64
65
66
67
68
69
70 protected <T> PagedQuery createPagedQuery( CriteriaQuery<T> criteriaQuery, PaginationProperties paginationProperties )
71 {
72
73
74 EntityManager em = getEM( );
75 CriteriaBuilder cb = em.getCriteriaBuilder( );
76 CriteriaQuery<Long> countQuery = cb.createQuery( Long.class );
77 countQuery.select( cb.count( countQuery.from( criteriaQuery.getResultType( ) ) ) );
78
79
80
81 countQuery.getRoots( ).clear( );
82 for ( Root<?> root : criteriaQuery.getRoots( ) )
83 {
84 countQuery.getRoots( ).add( root );
85 }
86
87 if ( criteriaQuery.getRestriction( ) != null )
88 {
89 countQuery.where( criteriaQuery.getRestriction( ) ).distinct( true );
90 }
91
92
93 PagedQuerygins/stock/commons/dao/PagedQuery.html#PagedQuery">PagedQuery pq = new PagedQuery( em.createQuery( criteriaQuery ), em.createQuery( countQuery ), paginationProperties );
94
95 return pq;
96 }
97
98
99
100
101
102
103
104
105 public ResultList<E> findAll( PaginationProperties paginationProperties )
106 {
107
108 Query query = getEM( ).createQuery( "SELECT e FROM " + getEntityClassName( ) + " e " );
109
110 Query countQuery = getEM( ).createQuery( "SELECT count(e) FROM " + getEntityClassName( ) + " e " );
111
112 PagedQuerygins/stock/commons/dao/PagedQuery.html#PagedQuery">PagedQuery pq = new PagedQuery( query, countQuery, paginationProperties );
113 return pq.getResultList( );
114 }
115
116
117
118
119
120
121
122
123
124 protected void addRestriction( CriteriaQuery<?> query, Expression<Boolean> exp )
125 {
126 CriteriaBuilder builder = getEM( ).getCriteriaBuilder( );
127 Predicate restriction = query.getRestriction( );
128 if ( restriction == null )
129 {
130 query.where( exp );
131 }
132 else
133 {
134 query.where( builder.and( restriction, exp ) );
135 }
136 }
137 }