Skip to content

Commit 549b807

Browse files
committed
Polishing.
Reuse existing EvaluationContextProvider infrastructure and static parser/parser context instances. Parse expressions early. Update Javadoc to reflect SpEL support. Reformat code to use tabs instead of spaces. Rename types for consistency. Rename SpelExpressionResultSanitizer to SqlIdentifierSanitizer to express its intended usage. Eagerly initialize entities where applicable. Simplify code. See #1325 Original pull request: #1461
1 parent 68a13fe commit 549b807

File tree

13 files changed

+416
-300
lines changed

13 files changed

+416
-300
lines changed

spring-data-jdbc/src/main/java/org/springframework/data/jdbc/core/mapping/JdbcMappingContext.java

+1-2
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,7 @@ protected RelationalPersistentProperty createPersistentProperty(Property propert
8181
RelationalPersistentEntity<?> owner, SimpleTypeHolder simpleTypeHolder) {
8282
BasicJdbcPersistentProperty persistentProperty = new BasicJdbcPersistentProperty(property, owner, simpleTypeHolder,
8383
this.getNamingStrategy());
84-
persistentProperty.setForceQuote(isForceQuote());
85-
persistentProperty.setSpelExpressionProcessor(getSpelExpressionProcessor());
84+
applyDefaults(persistentProperty);
8685
return persistentProperty;
8786
}
8887

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
/*
2+
* Copyright 2017-2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.relational.core.mapping;
17+
18+
import java.util.Optional;
19+
20+
import org.springframework.data.mapping.model.BasicPersistentEntity;
21+
import org.springframework.data.relational.core.sql.SqlIdentifier;
22+
import org.springframework.data.util.Lazy;
23+
import org.springframework.data.util.TypeInformation;
24+
import org.springframework.expression.Expression;
25+
import org.springframework.expression.ParserContext;
26+
import org.springframework.expression.common.LiteralExpression;
27+
import org.springframework.expression.spel.standard.SpelExpressionParser;
28+
import org.springframework.lang.Nullable;
29+
import org.springframework.util.StringUtils;
30+
31+
/**
32+
* SQL-specific {@link RelationalPersistentEntity} implementation that adds SQL-specific meta-data such as the table and
33+
* schema name.
34+
*
35+
* @author Jens Schauder
36+
* @author Greg Turnquist
37+
* @author Bastian Wilhelm
38+
* @author Mikhail Polivakha
39+
* @author Kurt Niemi
40+
*/
41+
class BasicRelationalPersistentEntity<T> extends BasicPersistentEntity<T, RelationalPersistentProperty>
42+
implements RelationalPersistentEntity<T> {
43+
44+
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
45+
46+
private final Lazy<SqlIdentifier> tableName;
47+
private final @Nullable Expression tableNameExpression;
48+
49+
private final Lazy<Optional<SqlIdentifier>> schemaName;
50+
private final ExpressionEvaluator expressionEvaluator;
51+
private boolean forceQuote = true;
52+
53+
/**
54+
* Creates a new {@link BasicRelationalPersistentEntity} for the given {@link TypeInformation}.
55+
*
56+
* @param information must not be {@literal null}.
57+
*/
58+
BasicRelationalPersistentEntity(TypeInformation<T> information, NamingStrategy namingStrategy,
59+
ExpressionEvaluator expressionEvaluator) {
60+
61+
super(information);
62+
63+
this.expressionEvaluator = expressionEvaluator;
64+
65+
Lazy<Optional<SqlIdentifier>> defaultSchema = Lazy.of(() -> StringUtils.hasText(namingStrategy.getSchema())
66+
? Optional.of(createDerivedSqlIdentifier(namingStrategy.getSchema()))
67+
: Optional.empty());
68+
69+
if (isAnnotationPresent(Table.class)) {
70+
71+
Table table = getRequiredAnnotation(Table.class);
72+
73+
this.tableName = Lazy.of(() -> StringUtils.hasText(table.value()) ? createSqlIdentifier(table.value())
74+
: createDerivedSqlIdentifier(namingStrategy.getTableName(getType())));
75+
this.tableNameExpression = detectExpression(table.value());
76+
77+
this.schemaName = StringUtils.hasText(table.schema())
78+
? Lazy.of(() -> Optional.of(createSqlIdentifier(table.schema())))
79+
: defaultSchema;
80+
81+
} else {
82+
83+
this.tableName = Lazy.of(() -> createDerivedSqlIdentifier(namingStrategy.getTableName(getType())));
84+
this.tableNameExpression = null;
85+
this.schemaName = defaultSchema;
86+
}
87+
}
88+
89+
/**
90+
* Returns a SpEL {@link Expression} if the given {@link String} is actually an expression that does not evaluate to a
91+
* {@link LiteralExpression} (indicating that no subsequent evaluation is necessary).
92+
*
93+
* @param potentialExpression can be {@literal null}
94+
* @return can be {@literal null}.
95+
*/
96+
@Nullable
97+
private static Expression detectExpression(@Nullable String potentialExpression) {
98+
99+
if (!StringUtils.hasText(potentialExpression)) {
100+
return null;
101+
}
102+
103+
Expression expression = PARSER.parseExpression(potentialExpression, ParserContext.TEMPLATE_EXPRESSION);
104+
return expression instanceof LiteralExpression ? null : expression;
105+
}
106+
107+
private SqlIdentifier createSqlIdentifier(String name) {
108+
return isForceQuote() ? SqlIdentifier.quoted(name) : SqlIdentifier.unquoted(name);
109+
}
110+
111+
private SqlIdentifier createDerivedSqlIdentifier(String name) {
112+
return new DerivedSqlIdentifier(name, isForceQuote());
113+
}
114+
115+
public boolean isForceQuote() {
116+
return forceQuote;
117+
}
118+
119+
public void setForceQuote(boolean forceQuote) {
120+
this.forceQuote = forceQuote;
121+
}
122+
123+
@Override
124+
public SqlIdentifier getTableName() {
125+
126+
if (tableNameExpression == null) {
127+
return tableName.get();
128+
}
129+
130+
return createSqlIdentifier(expressionEvaluator.evaluate(tableNameExpression));
131+
}
132+
133+
@Override
134+
public SqlIdentifier getQualifiedTableName() {
135+
136+
SqlIdentifier schema;
137+
if (schemaNameExpression != null) {
138+
schema = createSqlIdentifier(expressionEvaluator.evaluate(schemaNameExpression));
139+
} else {
140+
schema = schemaName.get().orElse(null);
141+
}
142+
143+
if (schema == null) {
144+
return getTableName();
145+
}
146+
147+
return SqlIdentifier.from(schema, getTableName());
148+
}
149+
150+
@Override
151+
public SqlIdentifier getIdColumn() {
152+
return getRequiredIdProperty().getColumnName();
153+
}
154+
155+
@Override
156+
public String toString() {
157+
return String.format("BasicRelationalPersistentEntity<%s>", getType());
158+
}
159+
}

spring-data-relational/src/main/java/org/springframework/data/relational/core/mapping/BasicRelationalPersistentProperty.java

+56-20
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,19 @@
2525
import org.springframework.data.mapping.model.SimpleTypeHolder;
2626
import org.springframework.data.relational.core.mapping.Embedded.OnEmpty;
2727
import org.springframework.data.relational.core.sql.SqlIdentifier;
28+
import org.springframework.data.spel.EvaluationContextProvider;
2829
import org.springframework.data.util.Lazy;
2930
import org.springframework.data.util.Optionals;
31+
import org.springframework.expression.Expression;
32+
import org.springframework.expression.ParserContext;
33+
import org.springframework.expression.common.LiteralExpression;
34+
import org.springframework.expression.spel.standard.SpelExpressionParser;
35+
import org.springframework.lang.Nullable;
3036
import org.springframework.util.Assert;
3137
import org.springframework.util.StringUtils;
3238

3339
/**
34-
* Meta data about a property to be used by repository implementations.
40+
* SQL-specific {@link org.springframework.data.mapping.PersistentProperty} implementation.
3541
*
3642
* @author Jens Schauder
3743
* @author Greg Turnquist
@@ -42,14 +48,17 @@
4248
public class BasicRelationalPersistentProperty extends AnnotationBasedPersistentProperty<RelationalPersistentProperty>
4349
implements RelationalPersistentProperty {
4450

51+
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
52+
4553
private final Lazy<SqlIdentifier> columnName;
54+
private final @Nullable Expression columnNameExpression;
4655
private final Lazy<Optional<SqlIdentifier>> collectionIdColumnName;
4756
private final Lazy<SqlIdentifier> collectionKeyColumnName;
48-
private final Lazy<Boolean> isEmbedded;
49-
private final Lazy<String> embeddedPrefix;
57+
private final boolean isEmbedded;
58+
private final String embeddedPrefix;
5059
private final NamingStrategy namingStrategy;
5160
private boolean forceQuote = true;
52-
private SpelExpressionProcessor spelExpressionProcessor = new SpelExpressionProcessor();
61+
private ExpressionEvaluator spelExpressionProcessor = new ExpressionEvaluator(EvaluationContextProvider.DEFAULT);
5362

5463
/**
5564
* Creates a new {@link BasicRelationalPersistentProperty}.
@@ -84,19 +93,26 @@ public BasicRelationalPersistentProperty(Property property, PersistentEntity<?,
8493

8594
Assert.notNull(namingStrategy, "NamingStrategy must not be null");
8695

87-
this.isEmbedded = Lazy.of(() -> Optional.ofNullable(findAnnotation(Embedded.class)).isPresent());
96+
this.isEmbedded = isAnnotationPresent(Embedded.class);
8897

89-
this.embeddedPrefix = Lazy.of(() -> Optional.ofNullable(findAnnotation(Embedded.class)) //
98+
this.embeddedPrefix = Optional.ofNullable(findAnnotation(Embedded.class)) //
9099
.map(Embedded::prefix) //
91-
.orElse(""));
100+
.orElse("");
92101

93-
this.columnName = Lazy.of(() -> Optional.ofNullable(findAnnotation(Column.class)) //
94-
.map(Column::value) //
95-
.map(spelExpressionProcessor::applySpelExpression) //
96-
.filter(StringUtils::hasText) //
97-
.map(this::createSqlIdentifier) //
98-
.orElseGet(() -> createDerivedSqlIdentifier(namingStrategy.getColumnName(this))));
102+
if (isAnnotationPresent(Column.class)) {
103+
104+
Column column = getRequiredAnnotation(Column.class);
105+
106+
columnName = Lazy.of(() -> StringUtils.hasText(column.value()) ? createSqlIdentifier(column.value())
107+
: createDerivedSqlIdentifier(namingStrategy.getColumnName(this)));
108+
columnNameExpression = detectExpression(column.value());
99109

110+
} else {
111+
columnName = Lazy.of(() -> createDerivedSqlIdentifier(namingStrategy.getColumnName(this)));
112+
columnNameExpression = null;
113+
}
114+
115+
// TODO: support expressions for MappedCollection
100116
this.collectionIdColumnName = Lazy.of(() -> Optionals
101117
.toStream(Optional.ofNullable(findAnnotation(MappedCollection.class)) //
102118
.map(MappedCollection::idColumn), //
@@ -112,14 +128,29 @@ public BasicRelationalPersistentProperty(Property property, PersistentEntity<?,
112128
.map(this::createSqlIdentifier) //
113129
.orElseGet(() -> createDerivedSqlIdentifier(namingStrategy.getKeyColumn(this))));
114130
}
115-
public SpelExpressionProcessor getSpelExpressionProcessor() {
116-
return spelExpressionProcessor;
117-
}
118131

119-
public void setSpelExpressionProcessor(SpelExpressionProcessor spelExpressionProcessor) {
132+
void setSpelExpressionProcessor(ExpressionEvaluator spelExpressionProcessor) {
120133
this.spelExpressionProcessor = spelExpressionProcessor;
121134
}
122135

136+
/**
137+
* Returns a SpEL {@link Expression} if the given {@link String} is actually an expression that does not evaluate to a
138+
* {@link LiteralExpression} (indicating that no subsequent evaluation is necessary).
139+
*
140+
* @param potentialExpression can be {@literal null}
141+
* @return can be {@literal null}.
142+
*/
143+
@Nullable
144+
private static Expression detectExpression(@Nullable String potentialExpression) {
145+
146+
if (!StringUtils.hasText(potentialExpression)) {
147+
return null;
148+
}
149+
150+
Expression expression = PARSER.parseExpression(potentialExpression, ParserContext.TEMPLATE_EXPRESSION);
151+
return expression instanceof LiteralExpression ? null : expression;
152+
}
153+
123154
private SqlIdentifier createSqlIdentifier(String name) {
124155
return isForceQuote() ? SqlIdentifier.quoted(name) : SqlIdentifier.unquoted(name);
125156
}
@@ -148,7 +179,12 @@ public boolean isEntity() {
148179

149180
@Override
150181
public SqlIdentifier getColumnName() {
151-
return columnName.get();
182+
183+
if (columnNameExpression == null) {
184+
return columnName.get();
185+
}
186+
187+
return createSqlIdentifier(spelExpressionProcessor.evaluate(columnNameExpression));
152188
}
153189

154190
@Override
@@ -193,12 +229,12 @@ public boolean isOrdered() {
193229

194230
@Override
195231
public boolean isEmbedded() {
196-
return isEmbedded.get();
232+
return isEmbedded;
197233
}
198234

199235
@Override
200236
public String getEmbeddedPrefix() {
201-
return isEmbedded() ? embeddedPrefix.get() : null;
237+
return isEmbedded() ? embeddedPrefix : null;
202238
}
203239

204240
@Override

spring-data-relational/src/main/java/org/springframework/data/relational/core/mapping/Column.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@
3434
public @interface Column {
3535

3636
/**
37-
* The mapping column name.
37+
* The column name. The attribute supports SpEL expressions to dynamically calculate the column name on a
38+
* per-operation basis.
3839
*/
3940
String value() default "";
4041

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package org.springframework.data.relational.core.mapping;
2+
3+
import org.springframework.data.spel.EvaluationContextProvider;
4+
import org.springframework.expression.EvaluationException;
5+
import org.springframework.expression.Expression;
6+
import org.springframework.util.Assert;
7+
8+
/**
9+
* Provide support for processing SpEL expressions in @Table and @Column annotations, or anywhere we want to use SpEL
10+
* expressions and sanitize the result of the evaluated SpEL expression. The default sanitization allows for digits,
11+
* alphabetic characters and _ characters and strips out any other characters. Custom sanitization (if desired) can be
12+
* achieved by creating a class that implements the {@link SqlIdentifierSanitizer} interface and then invoking the
13+
* {@link #setSanitizer(SqlIdentifierSanitizer)} method.
14+
*
15+
* @author Kurt Niemi
16+
* @see SqlIdentifierSanitizer
17+
* @since 3.1
18+
*/
19+
class ExpressionEvaluator {
20+
21+
private EvaluationContextProvider provider;
22+
23+
private SqlIdentifierSanitizer sanitizer = SqlIdentifierSanitizer.words();
24+
25+
public ExpressionEvaluator(EvaluationContextProvider provider) {
26+
this.provider = provider;
27+
}
28+
29+
public String evaluate(Expression expression) throws EvaluationException {
30+
31+
Assert.notNull(expression, "Expression must not be null.");
32+
33+
String result = expression.getValue(provider.getEvaluationContext(null), String.class);
34+
return sanitizer.sanitize(result);
35+
}
36+
37+
public void setSanitizer(SqlIdentifierSanitizer sanitizer) {
38+
39+
Assert.notNull(sanitizer, "SqlIdentifierSanitizer must not be null");
40+
41+
this.sanitizer = sanitizer;
42+
}
43+
44+
public void setProvider(EvaluationContextProvider provider) {
45+
this.provider = provider;
46+
}
47+
}

0 commit comments

Comments
 (0)