jinlin
2025-04-10 af67fb927c3f30fa70df834f0e97f0b4a91e6119
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有,侵权必究!
 */
 
package com.example.client.service;
 
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.example.server.entity.BaseEntity;
import com.example.client.entity.PlatformEntity;
import com.example.client.entity.RenException;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
 
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * 基础服务接口,所有Service接口都要继承
 *
 * @author hehz
 */
public abstract class BaseService<Dao extends BaseMapper<Entity>, Entity extends BaseEntity> {
    @Autowired
    protected Dao baseDao;
 
    private Class<Entity> getEntityClass() {
        Class<Entity> entityClass = (Class<Entity>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[1];
        return entityClass;
    }
 
 
    public Entity get(Long id) {
        Entity entity = baseDao.selectById(id);
        return entity;
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void insert(Entity entity) {
        baseDao.insert(entity);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void update(Entity entity) {
        baseDao.updateById(entity);
    }
 
    /**
     * 根据 whereEntity 条件,更新记录
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Entity entity, Wrapper<Entity> updateWrapper) {
        baseDao.update(entity, updateWrapper);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void deleteLogic(Serializable id) {
        Entity entity = baseDao.selectById(id);
        if (entity != null) {
            if (entity instanceof PlatformEntity) {
                ((PlatformEntity) entity).setDelete(true);
                baseDao.updateById(entity);
            } else {
                baseDao.deleteById(id);
                // 处理附件,逻辑删除的不处理附件
            }
        }
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void deleteLogic(Long[] ids) {
        for (Long id : ids) {
            this.deleteLogic(id);
        }
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void deleteLogic(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            this.deleteLogic(id);
        }
    }
 
    @Transactional(rollbackFor = Exception.class)
    public void deleteLogic(List<Entity> entities) {
        for (Entity entity : entities) {
            this.deleteLogic(entity.getId());
        }
    }
 
    /**
     * <p>
     * 插入(批量),该方法不支持 Oracle、SQL Server
     * </p>
     *
     * @param entityList
     *            实体对象集合
     * @param batchSize
     *            插入批次数量
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean insertBatch(Collection<Entity> entityList, int batchSize) {
        SqlSession session = sqlSessionBatch();
        int i = 0;
        String sqlStatement = sqlStatement(SqlMethod.INSERT_ONE);
        try {
            for (Entity entity : entityList) {
                session.insert(sqlStatement, entity);
                if (i >= 1 && i % batchSize == 0) {
                    session.flushStatements();
                }
                i++;
            }
            session.flushStatements();
        } finally {
            closeSqlSession(session);
        }
        return true;
    }
 
    /**
     * <p>
     * 根据ID 批量更新
     * </p>
     *
     * @param entityList
     *            实体对象集合
     * @param batchSize
     *            更新批次数量
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateBatch(Collection<Entity> entityList, int batchSize) {
        if (CollectionUtils.isEmpty(entityList)) {
            throw new IllegalArgumentException("Error: entityList must not be empty");
        }
        SqlSession session = sqlSessionBatch();
        int i = 0;
        String sqlStatement = sqlStatement(SqlMethod.UPDATE_BY_ID);
        try {
            for (Entity entity : entityList) {
                MapperMethod.ParamMap<Entity> param = new MapperMethod.ParamMap<>();
                param.put(Constants.ENTITY, entity);
                session.update(sqlStatement, param);
                if (i >= 1 && i % batchSize == 0) {
                    session.flushStatements();
                }
                i++;
            }
            session.flushStatements();
        } finally {
            closeSqlSession(session);
        }
        return true;
    }
 
    /**
     * 保存关联关系
     *
     * @param relatedField1Name
     *            被关联的,以它为主
     * @param relatedField1Value
     * @param relatedField2Name
     * @param datas
     */
    public void saveRelatedDatas(String relatedField1Name, Long relatedField1Value, String relatedField2Name,
                                 List<Entity> datas) {
        List<Entity> all = baseDao.selectList(new QueryWrapper<Entity>().eq(relatedField1Name, relatedField1Value));
        Map<String, Entity> map = new HashMap<>();
        relatedField2Name = StrUtil.toCamelCase(relatedField2Name);// 转成驼峰
        for (Entity entity : all) {
            map.put(ReflectUtil.getFieldValue(entity, relatedField2Name).toString(), entity);
        }
        for (Entity data : datas) {
            String key = ReflectUtil.getFieldValue(data, relatedField2Name).toString();
            Entity db = map.get(key);
            if (db != null) {// 原来存在
                if (data instanceof PlatformEntity) {
                    if (((PlatformEntity) db).isDelete()) {
                        ((PlatformEntity) db).setDelete(false);
                        baseDao.updateById(db);
                    }
                }
                map.remove(key);
            } else {
                baseDao.insert(data);
            }
        }
        for (Entity entity : map.values()) {
            if (entity instanceof PlatformEntity) {
                ((PlatformEntity) entity).setDelete(true);
                baseDao.updateById(entity);
            } else {
                throw new RenException("业务模型异常!");
            }
        }
    }
 
    /**
     * <p>
     * 判断数据库操作是否成功
     * </p>
     * <p>
     * 注意!! 该方法为 Integer 判断,不可传入 int 基本类型
     * </p>
     *
     * @param result
     *            数据库操作返回影响条数
     * @return boolean
     */
    protected static boolean retBool(Integer result) {
        return SqlHelper.retBool(result);
    }
 
    /**
     * 获取SqlStatement
     *
     * @param sqlMethod
     * @return
     */
    protected String sqlStatement(SqlMethod sqlMethod) {
        return SqlHelper.table(currentModelClass()).getSqlStatement(sqlMethod.getMethod());
    }
 
    protected Class<Entity> currentModelClass() {
        return (Class<Entity>) ReflectionKit.getSuperClassGenericType(getClass(), 1);
    }
 
    /**
     * <p>
     * 批量操作 SqlSession
     * </p>
     */
    protected SqlSession sqlSessionBatch() {
        return SqlHelper.sqlSessionBatch(currentModelClass());
    }
 
    /**
     * 释放sqlSession
     *
     * @param sqlSession
     *            session
     */
    protected void closeSqlSession(SqlSession sqlSession) {
        SqlSessionUtils.closeSqlSession(sqlSession, GlobalConfigUtils.currentSessionFactory(currentModelClass()));
    }
 
 
}