/
MyBatisDataAccessStrategy.java
313 lines (263 loc) · 12.1 KB
/
MyBatisDataAccessStrategy.java
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*
* Copyright 2017-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jdbc.mybatis;
import static java.util.Arrays.*;
import java.util.Collections;
import java.util.Map;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jdbc.core.convert.CascadingDataAccessStrategy;
import org.springframework.data.jdbc.core.convert.DataAccessStrategy;
import org.springframework.data.jdbc.core.convert.DefaultDataAccessStrategy;
import org.springframework.data.jdbc.core.convert.DelegatingDataAccessStrategy;
import org.springframework.data.jdbc.core.convert.JdbcConverter;
import org.springframework.data.jdbc.core.convert.SqlGeneratorSource;
import org.springframework.data.mapping.PersistentPropertyPath;
import org.springframework.data.mapping.PropertyPath;
import org.springframework.data.relational.core.mapping.RelationalMappingContext;
import org.springframework.data.relational.core.mapping.RelationalPersistentProperty;
import org.springframework.data.relational.domain.Identifier;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.util.Assert;
/**
* {@link DataAccessStrategy} implementation based on MyBatis. Each method gets mapped to a statement. The name of the
* statement gets constructed as follows: By default, the namespace is based on the class of the entity plus the suffix
* "Mapper". This is then followed by the method name separated by a dot. For methods taking a {@link PropertyPath} as
* argument, the relevant entity is that of the root of the path, and the path itself gets as dot separated String
* appended to the statement name. Each statement gets an instance of {@link MyBatisContext}, which at least has the
* entityType set. For methods taking a {@link PropertyPath} the entityType if the context is set to the class of the
* leaf type.
*
* @author Jens Schauder
* @author Kazuki Shimizu
* @author Oliver Gierke
* @author Mark Paluch
*/
public class MyBatisDataAccessStrategy implements DataAccessStrategy {
private static final Logger LOG = LoggerFactory.getLogger(MyBatisDataAccessStrategy.class);
private final SqlSession sqlSession;
private NamespaceStrategy namespaceStrategy = NamespaceStrategy.DEFAULT_INSTANCE;
/**
* Create a {@link DataAccessStrategy} that first checks for queries defined by MyBatis and if it doesn't find one
* uses a {@link DefaultDataAccessStrategy}
*/
public static DataAccessStrategy createCombinedAccessStrategy(RelationalMappingContext context,
JdbcConverter converter, NamedParameterJdbcOperations operations, SqlSession sqlSession) {
return createCombinedAccessStrategy(context, converter, operations, sqlSession, NamespaceStrategy.DEFAULT_INSTANCE);
}
/**
* Create a {@link DataAccessStrategy} that first checks for queries defined by MyBatis and if it doesn't find one
* uses a {@link DefaultDataAccessStrategy}
*/
public static DataAccessStrategy createCombinedAccessStrategy(RelationalMappingContext context,
JdbcConverter converter, NamedParameterJdbcOperations operations, SqlSession sqlSession,
NamespaceStrategy namespaceStrategy) {
// the DefaultDataAccessStrategy needs a reference to the returned DataAccessStrategy. This creates a dependency
// cycle. In order to create it, we need something that allows to defer closing the cycle until all the elements are
// created. That is the purpose of the DelegatingAccessStrategy.
DelegatingDataAccessStrategy delegatingDataAccessStrategy = new DelegatingDataAccessStrategy();
MyBatisDataAccessStrategy myBatisDataAccessStrategy = new MyBatisDataAccessStrategy(sqlSession);
myBatisDataAccessStrategy.setNamespaceStrategy(namespaceStrategy);
CascadingDataAccessStrategy cascadingDataAccessStrategy = new CascadingDataAccessStrategy(
asList(myBatisDataAccessStrategy, delegatingDataAccessStrategy));
SqlGeneratorSource sqlGeneratorSource = new SqlGeneratorSource(context);
DefaultDataAccessStrategy defaultDataAccessStrategy = new DefaultDataAccessStrategy( //
sqlGeneratorSource, //
context, //
converter, //
operations //
);
delegatingDataAccessStrategy.setDelegate(defaultDataAccessStrategy);
return cascadingDataAccessStrategy;
}
/**
* Constructs a {@link DataAccessStrategy} based on MyBatis.
* <p>
* Use a {@link SqlSessionTemplate} for {@link SqlSession} or a similar implementation tying the session to the proper
* transaction. Note that the resulting {@link DataAccessStrategy} only handles MyBatis. It does not include the
* functionality of the {@link DefaultDataAccessStrategy} which one normally still wants. Use
* {@link #createCombinedAccessStrategy(RelationalMappingContext, JdbcConverter, NamedParameterJdbcOperations, SqlSession, NamespaceStrategy)}
* to create such a {@link DataAccessStrategy}.
*
* @param sqlSession Must be non {@literal null}.
*/
public MyBatisDataAccessStrategy(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
/**
* Set a NamespaceStrategy to be used.
*
* @param namespaceStrategy Must be non {@literal null}
*/
public void setNamespaceStrategy(NamespaceStrategy namespaceStrategy) {
Assert.notNull(namespaceStrategy, "The NamespaceStrategy must not be null");
this.namespaceStrategy = namespaceStrategy;
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#insert(java.lang.Object, java.lang.Class, java.util.Map)
*/
@Override
public <T> Object insert(T instance, Class<T> domainType, Map<String, Object> additionalParameters) {
MyBatisContext myBatisContext = new MyBatisContext(null, instance, domainType, additionalParameters);
sqlSession().insert(namespace(domainType) + ".insert", myBatisContext);
return myBatisContext.getId();
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#insert(java.lang.Object, java.lang.Class, ParentKeys)
*/
@Override
public <T> Object insert(T instance, Class<T> domainType, Identifier identifier) {
MyBatisContext myBatisContext = new MyBatisContext(null, instance, domainType, identifier.toMap());
sqlSession().insert(namespace(domainType) + ".insert", myBatisContext);
return myBatisContext.getId();
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#update(java.lang.Object, java.lang.Class)
*/
@Override
public <S> boolean update(S instance, Class<S> domainType) {
return sqlSession().update(namespace(domainType) + ".update",
new MyBatisContext(null, instance, domainType, Collections.emptyMap())) != 0;
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#delete(java.lang.Object, java.lang.Class)
*/
@Override
public void delete(Object id, Class<?> domainType) {
sqlSession().delete(namespace(domainType) + ".delete",
new MyBatisContext(id, null, domainType, Collections.emptyMap()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#delete(java.lang.Object, org.springframework.data.mapping.PersistentPropertyPath)
*/
@Override
public void delete(Object rootId, PersistentPropertyPath<RelationalPersistentProperty> propertyPath) {
sqlSession().delete(
namespace(propertyPath.getBaseProperty().getOwner().getType()) + ".delete-" + toDashPath(propertyPath),
new MyBatisContext(rootId, null, propertyPath.getRequiredLeafProperty().getTypeInformation().getType(),
Collections.emptyMap()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#deleteAll(java.lang.Class)
*/
@Override
public <T> void deleteAll(Class<T> domainType) {
sqlSession().delete( //
namespace(domainType) + ".deleteAll", //
new MyBatisContext(null, null, domainType, Collections.emptyMap()) //
);
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#deleteAll(org.springframework.data.mapping.PersistentPropertyPath)
*/
@Override
public void deleteAll(PersistentPropertyPath<RelationalPersistentProperty> propertyPath) {
Class<?> baseType = propertyPath.getBaseProperty().getOwner().getType();
Class<?> leafType = propertyPath.getRequiredLeafProperty().getTypeInformation().getType();
sqlSession().delete( //
namespace(baseType) + ".deleteAll-" + toDashPath(propertyPath), //
new MyBatisContext(null, null, leafType, Collections.emptyMap()) //
);
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#findById(java.lang.Object, java.lang.Class)
*/
@Override
public <T> T findById(Object id, Class<T> domainType) {
return sqlSession().selectOne(namespace(domainType) + ".findById",
new MyBatisContext(id, null, domainType, Collections.emptyMap()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#findAll(java.lang.Class)
*/
@Override
public <T> Iterable<T> findAll(Class<T> domainType) {
return sqlSession().selectList(namespace(domainType) + ".findAll",
new MyBatisContext(null, null, domainType, Collections.emptyMap()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#findAllById(java.lang.Iterable, java.lang.Class)
*/
@Override
public <T> Iterable<T> findAllById(Iterable<?> ids, Class<T> domainType) {
return sqlSession().selectList(namespace(domainType) + ".findAllById",
new MyBatisContext(ids, null, domainType, Collections.emptyMap()));
}
@Override
public Iterable<Object> findAllByPath(Identifier identifier,
PersistentPropertyPath<RelationalPersistentProperty> path) {
String statementName = namespace(path.getBaseProperty().getOwner().getType()) + ".findAllByPath-"
+ path.toDotPath();
try {
return sqlSession().selectList(statementName,
new MyBatisContext(identifier, null, path.getRequiredLeafProperty().getType()));
} catch (PersistenceException pex) {
LOG.debug(String.format("Didn't find %s in the MyBatis session. Falling back to findAllByPath.", statementName),
pex);
return DataAccessStrategy.super.findAllByPath(identifier, path);
}
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#findAllByProperty(java.lang.Object, org.springframework.data.relational.core.mapping.RelationalPersistentProperty)
*/
@Override
public <T> Iterable<T> findAllByProperty(Object rootId, RelationalPersistentProperty property) {
return sqlSession().selectList(
namespace(property.getOwner().getType()) + ".findAllByProperty-" + property.getName(),
new MyBatisContext(rootId, null, property.getType(), Collections.emptyMap()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#existsById(java.lang.Object, java.lang.Class)
*/
@Override
public <T> boolean existsById(Object id, Class<T> domainType) {
return sqlSession().selectOne(namespace(domainType) + ".existsById",
new MyBatisContext(id, null, domainType, Collections.emptyMap()));
}
/*
* (non-Javadoc)
* @see org.springframework.data.jdbc.core.DataAccessStrategy#count(java.lang.Class)
*/
@Override
public long count(Class<?> domainType) {
return sqlSession().selectOne(namespace(domainType) + ".count",
new MyBatisContext(null, null, domainType, Collections.emptyMap()));
}
private String namespace(Class<?> domainType) {
return this.namespaceStrategy.getNamespace(domainType);
}
private SqlSession sqlSession() {
return this.sqlSession;
}
private static String toDashPath(PersistentPropertyPath<RelationalPersistentProperty> propertyPath) {
return propertyPath.toDotPath().replaceAll("\\.", "-");
}
}