Skip to content

Commit 9b501ca

Browse files
committed
impl service layer for search
add classes need for new search platform also implement basic feature in service layer and add test method for that.
1 parent 9cb42d0 commit 9b501ca

5 files changed

Lines changed: 202 additions & 39 deletions

File tree

src/main/java/ir/bigz/springbootreal/commons/util/Utils.java

Lines changed: 83 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package ir.bigz.springbootreal.commons.util;
22

3+
import ir.bigz.springbootreal.dto.SqlOperation;
34
import ir.bigz.springbootreal.dto.ValueCondition;
45

56
import java.sql.Timestamp;
@@ -17,27 +18,28 @@ public class Utils {
1718
static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd - HH:mm:ss z");
1819
static final DateTimeFormatter SIMPLE_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd - HH:mm:ss");
1920

20-
public static String getTimeNow(){
21+
public static String getTimeNow() {
2122
return ZonedDateTime.now(ZoneId.of("Asia/Tehran")).format(FORMATTER);
2223
}
2324

24-
public static String getLocalTimeNow(){
25+
public static String getLocalTimeNow() {
2526
return LocalDateTime.now().format(SIMPLE_FORMATTER);
2627
}
2728

28-
public static Timestamp getTimestampNow(){
29+
public static Timestamp getTimestampNow() {
2930
return Timestamp.valueOf(LocalDateTime.now());
3031
}
3132

32-
public static String convertTimestamp(Timestamp timestamp){
33+
public static String convertTimestamp(Timestamp timestamp) {
3334
LocalDateTime localDateTime = timestamp.toLocalDateTime();
3435
return localDateTime.format(SIMPLE_FORMATTER);
3536
}
3637

37-
public static Timestamp convertTimeString(String time){
38+
public static Timestamp convertTimeString(String time) {
3839
LocalDateTime from = LocalDateTime.from(SIMPLE_FORMATTER.parse(time));
3940
return Timestamp.valueOf(from);
4041
}
42+
4143
public static boolean isNotNull(String s) {
4244
return !isNull(s);
4345
}
@@ -67,43 +69,107 @@ public static <T> T getQueryString(Map<String, String> queryString,
6769
String key,
6870
ValueCondition condition,
6971
T defaultValue,
70-
Class<T> type){
72+
Class<T> type) {
7173

72-
if(queryString == null){
74+
if (queryString == null) {
7375
return null;
7476
}
7577

7678
String value = queryString.get(key);
7779
T returnValue = null;
78-
if(type.equals(String.class)){
79-
returnValue = (T)"";
80+
if (type.equals(String.class)) {
81+
returnValue = (T) "";
8082
}
8183

82-
if(value != null){
83-
if(condition == EQUAL){
84+
if (value != null) {
85+
if (condition == EQUAL) {
8486
if (type.equals(Integer.class))
85-
returnValue = (T) Integer.valueOf(value);
87+
returnValue = (T) Integer.valueOf(value);
8688
if (type.equals(Double.class))
8789
returnValue = (T) Double.valueOf(value);
8890
if (type.equals(Long.class))
8991
returnValue = (T) Long.valueOf(value);
9092
if (type.equals(Boolean.class))
9193
returnValue = (T) Boolean.valueOf(value);
92-
if (type.equals(String.class)){
94+
if (type.equals(String.class)) {
9395
returnValue = (T) value;
9496
}
95-
}
96-
else if (condition == CONTAINS) returnValue = (T) ("%" + value + "%");
97+
} else if (condition == CONTAINS) returnValue = (T) ("%" + value + "%");
9798
else if (condition == STARTS_WITH) returnValue = (T) (value + "%");
9899
else if (condition == ENDS_WITH) returnValue = (T) ("%" + value);
99-
else if (condition == IN){
100+
else if (condition == IN) {
100101
String[] array = value.split(",");
101102
returnValue = (T) Arrays.asList(array);
102103
}
103-
}else if(isNotNull(defaultValue)){
104+
} else if (isNotNull(defaultValue)) {
104105
returnValue = defaultValue;
105106
}
106107

107108
return returnValue;
108109
}
110+
111+
public static <T> void buildNativeQueryCondition(Map<String, String> queryString,
112+
Map<String, String> conditionsMap,
113+
Map<String, Object> parametersMap,
114+
String fieldName,
115+
String parameter,
116+
SqlOperation operation,
117+
Class<T> type) {
118+
if (queryString != null) {
119+
String value = queryString.get(parameter);
120+
T parameterVal = null;
121+
String queryCondition = "";
122+
if (type.equals(String.class)) {
123+
parameterVal = (T) "";
124+
}
125+
if (value != null && !Utils.isNull(value)) {
126+
if (operation == SqlOperation.EQUAL ||
127+
operation == SqlOperation.NOT_EQUAL ||
128+
operation == SqlOperation.GREATER_THAN ||
129+
operation == SqlOperation.GREATER_THAN_OR_EQUAL ||
130+
operation == SqlOperation.LESS_THAN ||
131+
operation == SqlOperation.LESS_THAN_OR_EQUAL) {
132+
if (type.equals(Integer.class)) {
133+
parameterVal = (T) Integer.valueOf(value);
134+
}
135+
if (type.equals(Double.class)) {
136+
parameterVal = (T) Double.valueOf(value);
137+
}
138+
if (type.equals(Long.class)) {
139+
parameterVal = (T) Long.valueOf(value);
140+
}
141+
if (type.equals(Boolean.class)) {
142+
parameterVal = (T) Boolean.valueOf(value);
143+
}
144+
if (type.equals(String.class)) {
145+
parameterVal = (T) value;
146+
}
147+
parametersMap.put(parameter, parameterVal);
148+
queryCondition = "and " + fieldName + " " + operation.operationSign + " " + ":" + parameter;
149+
} else if (operation == SqlOperation.CONTAINS || operation == SqlOperation.NOT_CONTAINS) {
150+
if (type.equals(String.class)) {
151+
parametersMap.put(parameter, "%" + value + "%");
152+
queryCondition = "and " + fieldName + " " + operation.operationSign + " :" + parameter;
153+
}
154+
} else if (operation == SqlOperation.STARTS_WITH) {
155+
if (type.equals(String.class)) {
156+
parametersMap.put(parameter, value + "%");
157+
queryCondition = "and " + fieldName + " " + operation.operationSign + " " + ":" + parameter;
158+
}
159+
} else if (operation == SqlOperation.ENDS_WITH) {
160+
if (type.equals(String.class)) {
161+
parametersMap.put(parameter, "%" + value);
162+
queryCondition = "and " + fieldName + " " + operation.operationSign + " " + ":" + parameter;
163+
}
164+
} else if (operation == SqlOperation.IN) {
165+
String[] listArray = value.split(",");
166+
parametersMap.put(parameter, Arrays.asList(listArray));
167+
queryCondition = "and " + fieldName + " " + operation.operationSign + " (" + ":" + parameter + ")";
168+
}
169+
}
170+
171+
conditionsMap.put(parameter, queryCondition);
172+
}
173+
174+
}
109175
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package ir.bigz.springbootreal.dto;
2+
3+
public enum SqlOperation {
4+
5+
EQUAL("="),
6+
NOT_EQUAL("<>"),
7+
GREATER_THAN(">"),
8+
GREATER_THAN_OR_EQUAL(">="),
9+
LESS_THAN("<"),
10+
LESS_THAN_OR_EQUAL("<="),
11+
IN("in"),
12+
NOT_IN("not in"),
13+
CONTAINS("like"),
14+
STARTS_WITH("like"),
15+
ENDS_WITH("like"),
16+
NOT_CONTAINS("not like"),
17+
BETWEEN("between"),
18+
NOT_BETWEEN("not between");
19+
20+
public final String operationSign;
21+
22+
SqlOperation(String operationSign) {
23+
this.operationSign = operationSign;
24+
}
25+
26+
public String getOperationSign() {
27+
return operationSign;
28+
}
29+
}

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
package ir.bigz.springbootreal.service;
22

3+
import ir.bigz.springbootreal.dto.PageResult;
4+
import ir.bigz.springbootreal.dto.PagedQuery;
35
import ir.bigz.springbootreal.viewmodel.UserModel;
46
import ir.bigz.springbootreal.viewmodel.search.UserSearchDto;
57
import org.springframework.data.domain.Page;
68
import org.springframework.data.domain.Sort;
79
import org.springframework.stereotype.Service;
810

911
import java.util.List;
12+
import java.util.Map;
1013

1114
@Service
1215
public interface UserService {
@@ -24,4 +27,6 @@ public interface UserService {
2427
Page<UserModel> getUserSearchResult(UserSearchDto userSearchDto, String sortOrder, Sort.Direction direction, Integer pageNumber, Integer pageSize);
2528

2629
Page<UserModel> getAllUserPage(String sortOrder, Sort.Direction sortDirection, Integer pageNumber, Integer pageSize);
30+
31+
PageResult<UserModel> getUserSearchV2(Map<String, String> queryString, PagedQuery pagedQuery);
2732
}

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

Lines changed: 55 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
import ir.bigz.springbootreal.commons.util.Utils;
44
import ir.bigz.springbootreal.dal.UserRepository;
5+
import ir.bigz.springbootreal.dto.PageResult;
6+
import ir.bigz.springbootreal.dto.PagedQuery;
7+
import ir.bigz.springbootreal.dto.SqlOperation;
58
import ir.bigz.springbootreal.dto.entity.User;
69
import ir.bigz.springbootreal.dto.mapper.UserMapper;
710
import ir.bigz.springbootreal.exception.AppException;
@@ -26,6 +29,7 @@ public class UserServiceImpl implements UserService {
2629

2730
private final UserRepository userRepository;
2831
private final UserMapper userMapper;
32+
private static final String USER_QUERY = "select * from users where 1=1 ";
2933

3034

3135
public UserServiceImpl(UserRepository userRepository,
@@ -37,12 +41,12 @@ public UserServiceImpl(UserRepository userRepository,
3741

3842
@Override
3943
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
40-
@Cacheable(value = "userCache", key="#userId", condition = "#userId != null", unless = "#result==null")
44+
@Cacheable(value = "userCache", key = "#userId", condition = "#userId != null", unless = "#result==null")
4145
public UserModel getUser(Long userId) {
4246
try {
4347
Optional<User> user = userRepository.find(userId);
4448
return userMapper.userToUserModel(user.get());
45-
}catch (RuntimeException exception){
49+
} catch (RuntimeException exception) {
4650
throw AppException.newInstance(
4751
HttpErrorCode.ERR_10702,
4852
String.format("user with id, %s not found", userId)
@@ -54,7 +58,7 @@ public UserModel getUser(Long userId) {
5458
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
5559
public UserModel addUser(UserModel userModel) {
5660
try {
57-
if(userRepository.getUserWithNationalCode(userModel.getNationalCode()) == null){
61+
if (userRepository.getUserWithNationalCode(userModel.getNationalCode()) == null) {
5862
userModel.setInsertDate(Utils.getLocalTimeNow());
5963
userModel.setActiveStatus(true);
6064
User user = userMapper.userModelToUser(userModel);
@@ -63,7 +67,7 @@ public UserModel addUser(UserModel userModel) {
6367
}
6468
throw new RuntimeException("user has already exist");
6569

66-
}catch (RuntimeException exception){
70+
} catch (RuntimeException exception) {
6771
throw AppException.newInstance(
6872
HttpErrorCode.ERR_10700, String.format("user has already existed with %s nationalId", userModel.getNationalCode())
6973
);
@@ -72,7 +76,7 @@ public UserModel addUser(UserModel userModel) {
7276

7377
@Override
7478
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
75-
@CachePut(value = "userCache", key="#userId", condition = "#userId != null", unless = "#result==null")
79+
@CachePut(value = "userCache", key = "#userId", condition = "#userId != null", unless = "#result==null")
7680
public UserModel updateUser(long userId, UserModel userModel) {
7781
try {
7882
Optional<User> user = userRepository.find(userId);
@@ -81,7 +85,7 @@ public UserModel updateUser(long userId, UserModel userModel) {
8185
mapUserForUpdate(sourceUser, updateUser);
8286
sourceUser.setUpdateDate(Utils.getTimestampNow());
8387
return userMapper.userToUserModel(sourceUser);
84-
}catch (RuntimeException exception){
88+
} catch (RuntimeException exception) {
8589
throw AppException.newInstance(
8690
HttpErrorCode.ERR_10703,
8791
String.format("user with userId %s, not found", userId)
@@ -92,13 +96,13 @@ public UserModel updateUser(long userId, UserModel userModel) {
9296

9397
@Override
9498
@CacheEvict(value = "userCache", beforeInvocation = true, key = "#userId")
95-
public String deleteUser(long userId){
96-
try{
99+
public String deleteUser(long userId) {
100+
try {
97101
userRepository.find(userId);
98102
userRepository.delete(userId);
99103
return "Success";
100104

101-
}catch (RuntimeException exception){
105+
} catch (RuntimeException exception) {
102106
throw AppException.newInstance(
103107
HttpErrorCode.ERR_10701,
104108
String.format("user with id %s, not found", userId)
@@ -112,7 +116,7 @@ public List<UserModel> getAll() {
112116
try {
113117
Stream<User> allUser = userRepository.getAll();
114118
return allUser.map(userMapper::userToUserModel).collect(Collectors.toList());
115-
}catch (RuntimeException exception){
119+
} catch (RuntimeException exception) {
116120
throw AppException.newInstance(
117121
HttpErrorCode.ERR_10701,
118122
String.format("getAll method has error: %s", exception.getCause())
@@ -130,7 +134,7 @@ public Page<UserModel> getUserSearchResult(UserSearchDto userSearchDto, String s
130134
Page<User> users = userRepository.getUserSearchResult(userSearchDto, order, pageable);
131135
List<UserModel> collect = users.get().map(userMapper::userToUserModel).collect(Collectors.toList());
132136
return new PageImpl<>(collect, pageable, users.getTotalElements());
133-
}catch (RuntimeException exception){
137+
} catch (RuntimeException exception) {
134138
throw AppException.newInstance(
135139
HttpErrorCode.ERR_10701,
136140
String.format("getAll method has error: %s", exception.getCause())
@@ -142,38 +146,68 @@ public Page<UserModel> getUserSearchResult(UserSearchDto userSearchDto, String s
142146

143147
@Override
144148
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
145-
public Page<UserModel> getAllUserPage(String sortOrder, Sort.Direction direction, Integer pageNumber, Integer pageSize){
149+
public Page<UserModel> getAllUserPage(String sortOrder, Sort.Direction direction, Integer pageNumber, Integer pageSize) {
146150
Sort.Order order = new Sort.Order(direction, sortOrder);
147151
Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by(order));
148152
Page<User> all = userRepository.getAll(pageable);
149153
List<UserModel> collect = all.get().map(userMapper::userToUserModel).collect(Collectors.toList());
150154
return new PageImpl<>(collect, pageable, all.getTotalElements());
151155
}
152156

153-
private void mapUserForUpdate(User sourceUser, User updateUser){
154-
if(!sourceUser.getFirstName().equals(updateUser.getFirstName())){
157+
@Override
158+
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
159+
public PageResult<UserModel> getUserSearchV2(Map<String, String> queryString, PagedQuery pagedQuery) {
160+
Map<String, Object> parametersMap = new HashMap<>();
161+
Map<String, String> conditionsMap = new HashMap<>();
162+
StringBuffer stringBuffer = new StringBuffer();
163+
stringBuffer.append(USER_QUERY);
164+
Utils.buildNativeQueryCondition(queryString,
165+
conditionsMap,
166+
parametersMap,
167+
"first_name",
168+
"firstName",
169+
SqlOperation.CONTAINS,
170+
String.class);
171+
172+
conditionsMap.keySet().forEach(s -> stringBuffer.append(conditionsMap.get(s)));
173+
174+
PageResult<User> userPageResult = userRepository.pageCreateQuery(stringBuffer.toString(), pagedQuery, parametersMap);
175+
176+
List<UserModel> collect = userPageResult.getResult().stream().map(userMapper::userToUserModel).collect(Collectors.toList());
177+
178+
PageResult<UserModel> userModelPageResult = new PageResult<>(collect,
179+
userPageResult.getPageSize(),
180+
userPageResult.getPageNumber(),
181+
userPageResult.getOffset(),
182+
userPageResult.getTotal());
183+
184+
return userModelPageResult;
185+
}
186+
187+
private void mapUserForUpdate(User sourceUser, User updateUser) {
188+
if (!sourceUser.getFirstName().equals(updateUser.getFirstName())) {
155189
sourceUser.setFirstName(updateUser.getFirstName());
156190
}
157-
if(!sourceUser.getLastName().equals(updateUser.getLastName())){
191+
if (!sourceUser.getLastName().equals(updateUser.getLastName())) {
158192
sourceUser.setLastName(updateUser.getLastName());
159193
}
160-
if(!sourceUser.getUserName().equals(updateUser.getUserName())){
194+
if (!sourceUser.getUserName().equals(updateUser.getUserName())) {
161195
sourceUser.setUserName(updateUser.getUserName());
162196
}
163-
if(!sourceUser.getNationalCode().equals(updateUser.getNationalCode())){
197+
if (!sourceUser.getNationalCode().equals(updateUser.getNationalCode())) {
164198
sourceUser.setNationalCode(updateUser.getNationalCode());
165199
}
166-
if(!sourceUser.getEmail().equals(updateUser.getEmail())){
200+
if (!sourceUser.getEmail().equals(updateUser.getEmail())) {
167201
sourceUser.setEmail(updateUser.getEmail());
168202
}
169-
if(!sourceUser.getMobile().equals(updateUser.getMobile())){
203+
if (!sourceUser.getMobile().equals(updateUser.getMobile())) {
170204
sourceUser.setMobile(updateUser.getMobile());
171205
}
172-
if(!sourceUser.getGender().equals(updateUser.getGender())){
206+
if (!sourceUser.getGender().equals(updateUser.getGender())) {
173207
sourceUser.setGender(updateUser.getGender());
174208
}
175209

176-
if(!sourceUser.isActiveStatus() == (updateUser.isActiveStatus())){
210+
if (!sourceUser.isActiveStatus() == (updateUser.isActiveStatus())) {
177211
sourceUser.setActiveStatus(updateUser.isActiveStatus());
178212
}
179213
}

0 commit comments

Comments
 (0)