Skip to content

Commit 111f92e

Browse files
committed
some clean code before add search v2 for criteria builder
1 parent 916aafb commit 111f92e

6 files changed

Lines changed: 44 additions & 45 deletions

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ This project, implement instance of basic feature, <br> you maybe want use for A
6363
3 - dynamic order and direction for sort data handle in daoRepository <br>
6464
4 - more detail about search feature, see searchEngineV2.drawio <br>
6565
5 - sample rest search request: <br>
66-
- http://localhost:9090/api/v1/user/search/v2?firstName=h&orderBy=firstName_asc, gender_desc&page=1&size=5 <br>
66+
- http://localhost:9090/api/v2/user/search?firstName=h&orderBy=firstName_asc, gender_desc&page=1&size=5 <br>
6767

6868
### test feature
6969
1 - generate sample data baseOn model with javaFaker <br>

pom.xml

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
44
<modelVersion>4.0.0</modelVersion>
55
<parent>
66
<groupId>org.springframework.boot</groupId>
77
<artifactId>spring-boot-starter-parent</artifactId>
88
<version>2.4.5</version>
9-
<relativePath/> <!-- lookup parent from repository -->
9+
<relativePath/>
10+
<!-- lookup parent from repository -->
1011
</parent>
1112
<groupId>ir.bigz</groupId>
1213
<artifactId>springboot-real</artifactId>
@@ -34,9 +35,9 @@
3435
</profile>
3536
<profile>
3637
<id>docker</id>
37-
<!-- <activation>-->
38-
<!-- <activeByDefault>true</activeByDefault>-->
39-
<!-- </activation>-->
38+
<!-- <activation>-->
39+
<!-- <activeByDefault>true</activeByDefault>-->
40+
<!-- </activation>-->
4041
<properties>
4142
<spring.profiles.active>docker</spring.profiles.active>
4243
</properties>
@@ -225,14 +226,14 @@
225226
<executions>
226227
<execution>
227228
<goals>
228-
<!-- <goal>addSources</goal>-->
229-
<!-- <goal>addTestSources</goal>-->
230-
<!-- <goal>generateStubs</goal>-->
231-
<goal>compile</goal>
232-
<!-- <goal>generateTestStubs</goal>-->
233-
<goal>compileTests</goal>
234-
<!-- <goal>removeStubs</goal>-->
235-
<!-- <goal>removeTestStubs</goal>-->
229+
<!-- <goal>addSources</goal>-->
230+
<!-- <goal>addTestSources</goal>-->
231+
<!-- <goal>generateStubs</goal>-->
232+
<goal>compile</goal>
233+
<!-- <goal>generateTestStubs</goal>-->
234+
<goal>compileTests</goal>
235+
<!-- <goal>removeStubs</goal>-->
236+
<!-- <goal>removeTestStubs</goal>-->
236237
</goals>
237238
</execution>
238239
</executions>
@@ -247,6 +248,12 @@
247248
<source>11</source>
248249
<target>11</target>
249250
<annotationProcessorPaths>
251+
<!-- static metaModel -->
252+
<annotationProcessorPath>
253+
<groupId>org.hibernate</groupId>
254+
<artifactId>hibernate-jpamodelgen</artifactId>
255+
<version>5.5.6.Final</version>
256+
</annotationProcessorPath>
250257
<path>
251258
<groupId>org.mapstruct</groupId>
252259
<artifactId>mapstruct-processor</artifactId>

src/main/java/ir/bigz/springbootreal/configuration/HikariDataSourceInit.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@ public class HikariDataSourceInit{
2828

2929
@Bean(name = "HikariDataSourceInit")
3030
public DataSource dataSource(){
31-
// HikariConfig hikariConfig = new HikariConfig(hikariProperties()); // use for production
32-
HikariConfig hikariConfig = new HikariConfig();
33-
hikariConfig.setDataSource(InitDataSource());
31+
HikariConfig hikariConfig = new HikariConfig(hikariProperties()); // use for production
32+
// HikariConfig hikariConfig = new HikariConfig();
33+
// hikariConfig.setDataSource(InitDataSource());
3434
int cpuCores = Runtime.getRuntime().availableProcessors();
3535
hikariConfig.setMaximumPoolSize(cpuCores * 4);
3636
hikariConfig.setConnectionTimeout(Long.parseLong(env.getProperty("hikari.connectionTimeout")));

src/main/java/ir/bigz/springbootreal/controller/SampleController.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
@RestController
1818
@CrossOrigin
19-
@RequestMapping("/api/v1")
19+
@RequestMapping("/api")
2020
public class SampleController extends AbstractController{
2121

2222
final
@@ -26,29 +26,29 @@ public SampleController(UserService userService) {
2626
this.userService = userService;
2727
}
2828

29-
@GetMapping(path = "/user/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
29+
@GetMapping(path = "/v1/user/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
3030
@ResponseStatus(HttpStatus.OK)
3131
public ResponseEntity<?> getUserById(@PathVariable("id") long id) {
3232
UserModel userModel = userService.getUser(id);
3333
return ResponseEntity.ok(userModel);
3434
}
3535

36-
@PostMapping(path = "/user/add", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
36+
@PostMapping(path = "/v1/user/add", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
3737
@ResponseStatus(HttpStatus.CREATED)
3838
public ResponseEntity<?> addUser(@Valid @RequestBody UserModel userModel) {
3939
UserModel userModelResult = userService.addUser(userModel);
4040
return ResponseEntity.status(HttpStatus.CREATED).body(userModelResult);
4141
}
4242

43-
@PostMapping(path = "/user/update/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
43+
@PostMapping(path = "/v1/user/update/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
4444
@ResponseStatus(HttpStatus.ACCEPTED)
4545
public ResponseEntity<?> updateUser(@RequestBody UserModel userModel, @PathVariable("id") long userId) {
4646
UserModel userModelResult = userService.updateUser(userId, userModel);
4747
return ResponseEntity.status(HttpStatus.ACCEPTED).body(userModelResult);
4848
}
4949

5050

51-
@PostMapping(path = "/user/delete/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
51+
@PostMapping(path = "/v1/user/delete/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
5252
@ResponseStatus(HttpStatus.ACCEPTED)
5353
public ResponseEntity<?> deleteUser(@PathVariable("id") long userId) {
5454
String result = userService.deleteUser(userId);
@@ -58,14 +58,14 @@ public ResponseEntity<?> deleteUser(@PathVariable("id") long userId) {
5858
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
5959
}
6060

61-
@GetMapping(path = "/user/all", produces = MediaType.APPLICATION_JSON_VALUE)
61+
@GetMapping(path = "/v1/user/all", produces = MediaType.APPLICATION_JSON_VALUE)
6262
@ResponseStatus(HttpStatus.OK)
6363
public ResponseEntity<?> getAllUser() {
6464
List<UserModel> result = userService.getAll();
6565
return ResponseEntity.ok(result);
6666
}
6767

68-
@GetMapping(path = "/user/search", produces = MediaType.APPLICATION_JSON_VALUE)
68+
@GetMapping(path = "/v1/user/search", produces = MediaType.APPLICATION_JSON_VALUE)
6969
@ResponseStatus(HttpStatus.OK)
7070
public ResponseEntity<?> getUserWithSearch(@RequestBody UserSearchDto userSearchDto,
7171
@RequestParam(name = "sortorder", defaultValue = "id") String sortOrder,
@@ -76,15 +76,15 @@ public ResponseEntity<?> getUserWithSearch(@RequestBody UserSearchDto userSearch
7676
return ResponseEntity.ok(userPageResult);
7777
}
7878

79-
@GetMapping(path = "/user/search/v2", produces = MediaType.APPLICATION_JSON_VALUE)
79+
@GetMapping(path = "/v2/user/search", produces = MediaType.APPLICATION_JSON_VALUE)
8080
@ResponseStatus(HttpStatus.OK)
8181
public ResponseEntity<?> getUserWithSearchV2() {
8282
PageResult<UserModel> userPageResult = userService.getUserSearchV2(getQueryString(), getPagedQuery());
8383
return ResponseEntity.ok(userPageResult);
8484
}
8585

8686

87-
@GetMapping(path = "/user/all/pagerquest", produces = MediaType.APPLICATION_JSON_VALUE)
87+
@GetMapping(path = "/v1/user/all/pagerquest", produces = MediaType.APPLICATION_JSON_VALUE)
8888
@ResponseStatus(HttpStatus.OK)
8989
public ResponseEntity<?> getAllUserPage(@RequestParam(name = "sortorder", required = false) String sortOrder,
9090
@RequestParam(name = "direction") String sortDirection,

src/main/java/ir/bigz/springbootreal/dal/DaoRepositoryImpl.java

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ public List<T> genericSearch(String query) {
130130
return entityManager.createQuery(query, daoType).getResultList();
131131
}
132132

133+
@SuppressWarnings("unchecked")
133134
@Override
134135
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
135136
public List<T> nativeQuery(String query, Map<String, Object> parameters) {
@@ -139,11 +140,12 @@ public List<T> nativeQuery(String query, Map<String, Object> parameters) {
139140
return nativeQuery.getResultList();
140141
}
141142

143+
@SuppressWarnings("unchecked")
142144
@Override
143145
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
144146
public PageResult<T> pageCreateQuery(String nativeQuery, PagedQuery pagedQuery, Map<String, Object> parameterMap, boolean getTotalCount) {
145147

146-
StringBuffer orderString = new StringBuffer();
148+
StringBuilder orderString = new StringBuilder();
147149
String queryString = nativeQuery;
148150
pagedQuery.getOrdering().forEach(
149151
orderParam -> {
@@ -182,13 +184,6 @@ public PageResult<T> pageCreateQuery(String nativeQuery, PagedQuery pagedQuery,
182184
if (pagedQuery.getPageSize() > 0 && pagedQuery.getPageSize() < maxPageSize && pagedQuery.getPageNumber() > 0) {
183185
int start = ((pagedQuery.getPageNumber() - 1) * pagedQuery.getPageSize());
184186
int end = (pagedQuery.getPageNumber() * pagedQuery.getPageSize());
185-
186-
// queryString = MessageFormat.format(
187-
// "SELECT * FROM ( " +
188-
// " SELECT q.*, rownum r_ FROM ({0}) q " +
189-
// " WHERE rownum < {1,number,#}) " +
190-
// "WHERE r_ >= {2,number,#} ", queryString, end, start);
191-
192187
query.setFirstResult(start);
193188
query.setMaxResults(end);
194189
}
@@ -200,14 +195,13 @@ public PageResult<T> pageCreateQuery(String nativeQuery, PagedQuery pagedQuery,
200195
total = totalCountOfSearch(queryString, parameterMap);
201196
}
202197

203-
PageResult<T> pagedResult = new PageResult<T>(
198+
return new PageResult<>(
204199
resultQuery
205200
, (pagedQuery.getPageSize() > -1 ? pagedQuery.getPageSize() : resultQuery.size())
206201
, pagedQuery.getPageNumber()
207202
, pagedQuery.getOffset()
208203
, total != 0 ? total : resultQuery.size()
209204
);
210-
return pagedResult;
211205
}
212206

213207
@Override

src/main/java/ir/bigz/springbootreal/service/UserServiceImpl.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,9 @@ public PageResult<UserModel> getUserSearchV2(Map<String, String> queryString, Pa
160160

161161
Map<String, Object> parametersMap = new HashMap<>();
162162
Map<String, String> conditionsMap = new HashMap<>();
163-
StringBuffer stringBuffer = new StringBuffer();
164-
stringBuffer.append(USER_QUERY); //base query
165-
stringBuffer.append(Utils.getWhereSimple()); //add where to query
163+
StringBuilder stringBuilder = new StringBuilder();
164+
stringBuilder.append(USER_QUERY); //base query
165+
stringBuilder.append(Utils.getWhereSimple()); //add where to query
166166
Map<String, String> parameterQueryWithFieldNameMap = new HashMap<>(); //map between queryString and entityColumn
167167
parameterQueryWithFieldNameMap.put("firstName", "first_name");
168168
parameterQueryWithFieldNameMap.put("lastName", "last_name");
@@ -177,19 +177,17 @@ public PageResult<UserModel> getUserSearchV2(Map<String, String> queryString, Pa
177177
parameterQueryWithOperationMap,
178178
String.class);
179179

180-
conditionsMap.keySet().forEach(s -> stringBuffer.append(conditionsMap.get(s)));
180+
conditionsMap.keySet().forEach(s -> stringBuilder.append(conditionsMap.get(s)));
181181

182-
PageResult<User> userPageResult = userRepository.pageCreateQuery(stringBuffer.toString(), pagedQuery, parametersMap, true);
182+
PageResult<User> userPageResult = userRepository.pageCreateQuery(stringBuilder.toString(), pagedQuery, parametersMap, true);
183183

184184
List<UserModel> collect = userPageResult.getResult().stream().map(userMapper::userToUserModel).collect(Collectors.toList());
185185

186-
PageResult<UserModel> userModelPageResult = new PageResult<>(collect,
186+
return new PageResult<>(collect,
187187
userPageResult.getPageSize(),
188188
userPageResult.getPageNumber(),
189189
userPageResult.getOffset(),
190190
userPageResult.getTotal());
191-
192-
return userModelPageResult;
193191
}
194192

195193
private void mapUserForUpdate(User sourceUser, User updateUser) {

0 commit comments

Comments
 (0)