Skip to content

Commit 5696d25

Browse files
committed
refactor: 优化
1 parent ea0906e commit 5696d25

File tree

10 files changed

+110
-39
lines changed

10 files changed

+110
-39
lines changed

hsweb-commons/hsweb-commons-crud/src/main/java/org/hswebframework/web/crud/configuration/JdbcSqlExecutorConfiguration.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,14 @@
2020
public class JdbcSqlExecutorConfiguration {
2121
@Bean
2222
@ConditionalOnMissingBean
23-
public SyncSqlExecutor syncSqlExecutor() {
24-
return new DefaultJdbcExecutor();
23+
public SyncSqlExecutor syncSqlExecutor(DataSource dataSource) {
24+
return new DefaultJdbcExecutor(dataSource);
2525
}
2626

2727
@Bean
2828
@ConditionalOnMissingBean
29-
public ReactiveSqlExecutor reactiveSqlExecutor() {
30-
return new DefaultJdbcReactiveExecutor();
29+
public ReactiveSqlExecutor reactiveSqlExecutor(DataSource dataSource) {
30+
return new DefaultJdbcReactiveExecutor(dataSource);
3131
}
3232

3333
}

hsweb-commons/hsweb-commons-crud/src/main/java/org/hswebframework/web/crud/service/CrudService.java

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package org.hswebframework.web.crud.service;
22

3+
import lombok.SneakyThrows;
34
import org.apache.commons.collections4.CollectionUtils;
45
import org.hswebframework.ezorm.core.param.QueryParam;
56
import org.hswebframework.ezorm.rdb.mapping.SyncDelete;
@@ -12,6 +13,7 @@
1213
import org.hswebframework.web.api.crud.entity.TransactionManagers;
1314
import org.springframework.transaction.annotation.Transactional;
1415

16+
import java.sql.SQLException;
1517
import java.util.Collection;
1618
import java.util.Collections;
1719
import java.util.List;
@@ -33,12 +35,14 @@ default SyncDelete createDelete() {
3335
}
3436

3537
@Transactional( readOnly = true, transactionManager = TransactionManagers.jdbcTransactionManager)
38+
@SneakyThrows
3639
default Optional<E> findById(K id) {
3740
return getRepository()
3841
.findById(id);
3942
}
4043

4144
@Transactional(readOnly = true, transactionManager = TransactionManagers.jdbcTransactionManager)
45+
@SneakyThrows
4246
default List<E> findById(Collection<K> id) {
4347
if (CollectionUtils.isEmpty(id)) {
4448
return Collections.emptyList();
@@ -49,69 +53,77 @@ default List<E> findById(Collection<K> id) {
4953
}
5054

5155
@Transactional(rollbackFor = Throwable.class,transactionManager = TransactionManagers.jdbcTransactionManager)
56+
@SneakyThrows
5257
default SaveResult save(Collection<E> entityArr) {
5358
return getRepository()
5459
.save(entityArr);
5560
}
5661

5762
@Transactional(rollbackFor = Throwable.class,transactionManager = TransactionManagers.jdbcTransactionManager)
63+
@SneakyThrows
5864
default int insert(Collection<E> entityArr) {
5965
return getRepository()
6066
.insertBatch(entityArr);
6167
}
6268

6369
@Transactional(rollbackFor = Throwable.class, transactionManager = TransactionManagers.jdbcTransactionManager)
64-
default void insert(E entityArr) {
65-
getRepository()
66-
.insert(entityArr);
70+
default void insert(E entityArr){
71+
getRepository().insert(entityArr);
6772
}
6873

6974
@Transactional(rollbackFor = Throwable.class,transactionManager = TransactionManagers.jdbcTransactionManager)
75+
@SneakyThrows
7076
default int updateById(K id, E entityArr) {
71-
return getRepository()
72-
.updateById(id, entityArr);
77+
return getRepository().updateById(id, entityArr);
7378
}
7479

7580
@Transactional(rollbackFor = Throwable.class,transactionManager = TransactionManagers.jdbcTransactionManager)
81+
@SneakyThrows
7682
default SaveResult save(E entity) {
7783
return getRepository()
7884
.save(Collections.singletonList(entity));
7985
}
8086

8187
@Transactional(rollbackFor = Throwable.class,transactionManager = TransactionManagers.jdbcTransactionManager)
88+
@SneakyThrows
8289
default SaveResult save(List<E> entities) {
8390
return getRepository()
8491
.save(entities);
8592
}
8693

8794
@Transactional(rollbackFor = Throwable.class,transactionManager = TransactionManagers.jdbcTransactionManager)
95+
@SneakyThrows
8896
default int deleteById(Collection<K> idArr) {
8997
return getRepository().deleteById(idArr);
9098
}
9199

92100
@Transactional(rollbackFor = Throwable.class,transactionManager = TransactionManagers.jdbcTransactionManager)
101+
@SneakyThrows
93102
default int deleteById(K idArr) {
94103
return deleteById(Collections.singletonList(idArr));
95104
}
96105

97106
@Transactional(readOnly = true, transactionManager = TransactionManagers.jdbcTransactionManager)
107+
@SneakyThrows
98108
default List<E> query(QueryParamEntity queryParam) {
99109
return createQuery().setParam(queryParam).fetch();
100110
}
101111

102112
@Transactional(readOnly = true, transactionManager = TransactionManagers.jdbcTransactionManager)
113+
@SneakyThrows
103114
default PagerResult<E> queryPager(QueryParamEntity param) {
104115

105116
int count = param.getTotal() == null ? count(param) : param.getTotal();
106117
if (count == 0) {
107-
return PagerResult.empty();
118+
return PagerResult.of(0,Collections.emptyList(),param);
108119
}
109120
param.rePaging(count);
110121

111122
return PagerResult.of(count, query(param), param);
112123
}
113124

114125
@Transactional(readOnly = true, transactionManager = TransactionManagers.jdbcTransactionManager)
126+
@SneakyThrows
115127
default int count(QueryParam param) {
116128
return getRepository()
117129
.createQuery()

hsweb-commons/hsweb-commons-crud/src/main/java/org/hswebframework/web/crud/sql/DefaultJdbcExecutor.java

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
package org.hswebframework.web.crud.sql;
22

3+
import lombok.Setter;
34
import lombok.extern.slf4j.Slf4j;
45
import org.hswebframework.ezorm.rdb.executor.SqlRequest;
56
import org.hswebframework.ezorm.rdb.executor.jdbc.JdbcSyncSqlExecutor;
67
import org.hswebframework.ezorm.rdb.executor.wrapper.ResultWrapper;
78
import org.hswebframework.web.api.crud.entity.TransactionManagers;
89
import org.hswebframework.web.datasource.DataSourceHolder;
910
import org.springframework.beans.factory.annotation.Autowired;
11+
import org.springframework.dao.support.PersistenceExceptionTranslator;
1012
import org.springframework.jdbc.datasource.DataSourceUtils;
13+
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
14+
import org.springframework.jdbc.support.SQLExceptionTranslator;
1115
import org.springframework.transaction.annotation.Propagation;
1216
import org.springframework.transaction.annotation.Transactional;
1317

@@ -25,6 +29,13 @@ public class DefaultJdbcExecutor extends JdbcSyncSqlExecutor {
2529
@Autowired
2630
private DataSource dataSource;
2731

32+
public DefaultJdbcExecutor() {
33+
}
34+
35+
public DefaultJdbcExecutor(DataSource dataSource) {
36+
this.dataSource = dataSource;
37+
}
38+
2839
protected String getDatasourceId() {
2940
return DataSourceHolder.switcher().datasource().current().orElse("default");
3041
}
@@ -33,8 +44,8 @@ protected String getDatasourceId() {
3344
public Connection getConnection(SqlRequest sqlRequest) {
3445

3546
DataSource dataSource = DataSourceHolder.isDynamicDataSourceReady() ?
36-
DataSourceHolder.currentDataSource().getNative() :
37-
this.dataSource;
47+
DataSourceHolder.currentDataSource().getNative() :
48+
this.dataSource;
3849
Connection connection = DataSourceUtils.getConnection(dataSource);
3950
boolean isConnectionTransactional = DataSourceUtils.isConnectionTransactional(connection, dataSource);
4051
if (log.isDebugEnabled()) {
@@ -50,8 +61,8 @@ public void releaseConnection(Connection connection, SqlRequest sqlRequest) {
5061
}
5162
try {
5263
DataSource dataSource = DataSourceHolder.isDynamicDataSourceReady() ?
53-
DataSourceHolder.currentDataSource().getNative() :
54-
this.dataSource;
64+
DataSourceHolder.currentDataSource().getNative() :
65+
this.dataSource;
5566
DataSourceUtils.doReleaseConnection(connection, dataSource);
5667
} catch (SQLException e) {
5768
log.error(e.getMessage(), e);

hsweb-commons/hsweb-commons-crud/src/main/java/org/hswebframework/web/crud/sql/DefaultJdbcReactiveExecutor.java

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,23 @@ public class DefaultJdbcReactiveExecutor extends JdbcReactiveSqlExecutor {
2424
@Autowired
2525
private DataSource dataSource;
2626

27+
@Deprecated
28+
public DefaultJdbcReactiveExecutor() {
29+
30+
}
31+
32+
public DefaultJdbcReactiveExecutor(DataSource dataSource) {
33+
this.dataSource = dataSource;
34+
}
35+
2736
protected String getDatasourceId() {
2837
return DataSourceHolder.switcher().datasource().current().orElse("default");
2938
}
3039

3140
private Tuple2<DataSource, Connection> getDataSourceAndConnection() {
3241
DataSource dataSource = DataSourceHolder.isDynamicDataSourceReady() ?
33-
DataSourceHolder.currentDataSource().getNative() :
34-
this.dataSource;
42+
DataSourceHolder.currentDataSource().getNative() :
43+
this.dataSource;
3544
Connection connection = DataSourceUtils.getConnection(dataSource);
3645
boolean isConnectionTransactional = DataSourceUtils.isConnectionTransactional(connection, dataSource);
3746
if (log.isDebugEnabled()) {
@@ -44,56 +53,56 @@ private Tuple2<DataSource, Connection> getDataSourceAndConnection() {
4453
@Override
4554
public Mono<Connection> getConnection() {
4655
return Mono
47-
.using(
48-
this::getDataSourceAndConnection
49-
,
50-
tp2 -> Mono.just(tp2.getT2()),
51-
tp2 -> DataSourceUtils.releaseConnection(tp2.getT2(), tp2.getT1()),
52-
false
53-
);
56+
.using(
57+
this::getDataSourceAndConnection
58+
,
59+
tp2 -> Mono.just(tp2.getT2()),
60+
tp2 -> DataSourceUtils.releaseConnection(tp2.getT2(), tp2.getT1()),
61+
false
62+
);
5463
}
5564

5665
@Override
5766
protected <T> Flux<T> doInConnection(Function<Connection, Publisher<T>> handler) {
5867
return Flux
5968
.using(this::getDataSourceAndConnection,
60-
tp2 -> handler.apply(tp2.getT2()),
61-
tp2 -> DataSourceUtils.releaseConnection(tp2.getT2(), tp2.getT1())
69+
tp2 -> handler.apply(tp2.getT2()),
70+
tp2 -> DataSourceUtils.releaseConnection(tp2.getT2(), tp2.getT1())
6271
);
6372
}
6473

6574
@Override
66-
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager,readOnly = true)
75+
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager, readOnly = true)
6776
public <E> Flux<E> select(String sql, ResultWrapper<E, ?> wrapper) {
68-
return super.select(sql,wrapper);
77+
return super.select(sql, wrapper);
6978
}
7079

7180
@Override
72-
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager,rollbackFor = Throwable.class)
81+
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager, rollbackFor = Throwable.class)
7382
public Mono<Integer> update(Publisher<SqlRequest> request) {
7483
return super.update(request);
7584
}
7685

7786
@Override
78-
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager,rollbackFor = Throwable.class)
87+
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager, rollbackFor = Throwable.class)
7988
public Mono<Integer> update(String sql, Object... args) {
80-
return super.update(sql,args);
89+
return super.update(sql, args);
8190
}
8291

8392
@Override
84-
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager,rollbackFor = Throwable.class)
93+
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager, rollbackFor = Throwable.class)
8594
public Mono<Integer> update(SqlRequest request) {
8695
return super.update(request);
8796
}
8897

8998
@Override
90-
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager,rollbackFor = Throwable.class)
99+
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager, rollbackFor = Throwable.class)
91100
public Mono<Void> execute(Publisher<SqlRequest> request) {
92101
return super.execute(request);
93102
}
94103

95104
@Override
96-
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager,rollbackFor = Throwable.class)
105+
@Transactional(transactionManager = TransactionManagers.jdbcTransactionManager, rollbackFor = Throwable.class)
97106
public Mono<Void> execute(SqlRequest request) {
98107
return super.execute(request);
99108
}

hsweb-commons/hsweb-commons-crud/src/main/java/org/hswebframework/web/crud/web/CommonErrorControllerAdvice.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
import org.hswebframework.web.i18n.LocaleUtils;
1414
import org.hswebframework.web.logger.ReactiveLogger;
1515
import org.springframework.core.annotation.Order;
16+
import org.springframework.dao.DataAccessException;
17+
import org.springframework.dao.DuplicateKeyException;
1618
import org.springframework.http.HttpStatus;
1719
import org.springframework.http.ResponseEntity;
1820
import org.springframework.transaction.TransactionException;
@@ -292,4 +294,21 @@ public Mono<ResponseMessage<Object>> handleException(I18nSupportException e) {
292294
.map(msg -> ResponseMessage.error(400, e.getI18nCode(), msg));
293295
}
294296

297+
@ExceptionHandler
298+
@ResponseStatus(HttpStatus.BAD_REQUEST)
299+
public Mono<ResponseMessage<Object>> handleException(DataAccessException e) {
300+
return LocaleUtils
301+
.resolveMessageReactive("error.data_access_failed")
302+
.map(msg -> ResponseMessage.error(400, "data_access_failed", msg));
303+
}
304+
305+
@ExceptionHandler
306+
@ResponseStatus(HttpStatus.BAD_REQUEST)
307+
public Mono<ResponseMessage<Object>> handleException(DuplicateKeyException e) {
308+
return LocaleUtils
309+
.resolveMessageReactive("error.duplicate_key")
310+
.map(msg -> ResponseMessage.error(400, "duplicate_key", msg));
311+
}
312+
313+
295314
}

hsweb-commons/hsweb-commons-crud/src/main/java/org/hswebframework/web/crud/web/CommonWebMvcErrorControllerAdvice.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
import org.hswebframework.web.i18n.LocaleUtils;
1414
import org.hswebframework.web.logger.ReactiveLogger;
1515
import org.springframework.core.annotation.Order;
16+
import org.springframework.dao.DataAccessException;
17+
import org.springframework.dao.DuplicateKeyException;
1618
import org.springframework.http.HttpStatus;
1719
import org.springframework.http.converter.HttpMessageNotReadableException;
1820
import org.springframework.validation.BindException;
@@ -243,4 +245,20 @@ public ResponseMessage<Object> handleException(I18nSupportException e) {
243245
return ResponseMessage.error(400, e.getI18nCode(), resolveMessage(e));
244246
}
245247

248+
@ExceptionHandler
249+
@ResponseStatus(HttpStatus.BAD_REQUEST)
250+
public ResponseMessage<Object> handleException(DataAccessException e){
251+
return ResponseMessage.error(400,
252+
"data_access_failed",
253+
LocaleUtils.resolveMessage("error.data_access_failed"));
254+
}
255+
256+
@ExceptionHandler
257+
@ResponseStatus(HttpStatus.BAD_REQUEST)
258+
public ResponseMessage<Object> handleException(DuplicateKeyException e){
259+
return ResponseMessage.error(400,
260+
"duplicate_key",
261+
LocaleUtils.resolveMessage("error.duplicate_key"));
262+
}
263+
246264
}

hsweb-commons/hsweb-commons-crud/src/main/resources/i18n/commons/messages_en.properties

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,6 @@ error.tree_entity_parent_id_not_exist=Parent node does not exist or has been del
99
error.resource_not_found=Resource not found
1010
error.data.find.not_found=Data not found
1111
error.sql.prepare.failed.IndexOutOfBoundsException=Execute SQL failed, try check config: `easyorm.dialect`.
12-
error.missing_request_body=Required request body is missing
12+
error.missing_request_body=Required request body is missing
13+
error.duplicate_key=Duplicate Data
14+
error.data_access_failed=Data Access Failed

hsweb-commons/hsweb-commons-crud/src/main/resources/i18n/commons/messages_zh.properties

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,6 @@ error.tree_entity_cyclic_dependency=\u4E0D\u80FD\u4FEE\u6539\u7236\u8282\u70B9\u
88
error.tree_entity_parent_id_not_exist=\u7236\u8282\u70B9\u4E0D\u5B58\u5728\u6216\u5DF2\u88AB\u5220\u9664
99
error.data.find.not_found=\u6570\u636E\u4E0D\u5B58\u5728
1010
error.sql.prepare.failed.IndexOutOfBoundsException=SQL\u6267\u884C\u5931\u8D25,\u8BF7\u5C1D\u8BD5\u68C0\u67E5`easyorm.dialect`\u914D\u7F6E.
11-
error.missing_request_body=\u8BF7\u6C42\u4F53\u7F3A\u5931
11+
error.missing_request_body=\u8BF7\u6C42\u4F53\u7F3A\u5931
12+
error.duplicate_key=\u5DF2\u5B58\u5728\u91CD\u590D\u7684\u6570\u636E
13+
error.data_access_failed=\u8BBF\u95EE\u6570\u636E\u5931\u8D25
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
1-
error.duplicate_key=Duplicate Data
21
error.user_already_exists=User already exists
32
error.user_not_found=The user does not exist or the id does not meet the rule
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
1-
error.duplicate_key=已存在重复的数据
2-
error.user_already_exists=用户已存在
3-
error.user_not_found=用户不存在或ID不符合规则:[{0}]
1+
error.user_already_exists=\u7528\u6237\u5DF2\u5B58\u5728
2+
error.user_not_found=\u7528\u6237\u4E0D\u5B58\u5728\u6216ID\u4E0D\u7B26\u5408\u89C4\u5219:[{0}]

0 commit comments

Comments
 (0)