Skip to content

Add Mapping for General Insert and Update that Renders null Values More Simply #343

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ Kotlin DSL.
- Added support for the "exists" and "not exists" operator in where clauses ([#296](https://github.com/mybatis/mybatis-dynamic-sql/pull/296))
- Refactored the built-in conditions ([#331](https://github.com/mybatis/mybatis-dynamic-sql/pull/331)) ([#336](https://github.com/mybatis/mybatis-dynamic-sql/pull/336))
- Added composition functions for WhereApplier ([#335](https://github.com/mybatis/mybatis-dynamic-sql/pull/335))
- Added a mapping for general insert and update statements that will render null values as "null" in the SQL ([#343](https://github.com/mybatis/mybatis-dynamic-sql/pull/343))

## Release 1.2.1 - September 29, 2020

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 the original author or authors.
* Copyright 2016-2021 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.
Expand Down Expand Up @@ -29,6 +29,7 @@
import org.mybatis.dynamic.sql.util.NullMapping;
import org.mybatis.dynamic.sql.util.StringConstantMapping;
import org.mybatis.dynamic.sql.util.ValueMapping;
import org.mybatis.dynamic.sql.util.ValueOrNullMapping;
import org.mybatis.dynamic.sql.util.ValueWhenPresentMapping;

public class GeneralInsertDSL implements Buildable<GeneralInsertModel> {
Expand Down Expand Up @@ -88,6 +89,15 @@ public GeneralInsertDSL toValue(Supplier<T> valueSupplier) {
return GeneralInsertDSL.this;
}

public GeneralInsertDSL toValueOrNull(T value) {
return toValueOrNull(() -> value);
}

public GeneralInsertDSL toValueOrNull(Supplier<T> valueSupplier) {
insertMappings.add(ValueOrNullMapping.of(column, valueSupplier));
return GeneralInsertDSL.this;
}

public GeneralInsertDSL toValueWhenPresent(T value) {
return toValueWhenPresent(() -> value);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 the original author or authors.
* Copyright 2016-2021 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.
Expand All @@ -26,6 +26,7 @@
import org.mybatis.dynamic.sql.util.NullMapping;
import org.mybatis.dynamic.sql.util.StringConstantMapping;
import org.mybatis.dynamic.sql.util.ValueMapping;
import org.mybatis.dynamic.sql.util.ValueOrNullMapping;
import org.mybatis.dynamic.sql.util.ValueWhenPresentMapping;

public class GeneralInsertValuePhraseVisitor extends GeneralInsertMappingVisitor<Optional<FieldAndValueAndParameters>> {
Expand All @@ -39,9 +40,7 @@ public GeneralInsertValuePhraseVisitor(RenderingStrategy renderingStrategy) {

@Override
public Optional<FieldAndValueAndParameters> visit(NullMapping mapping) {
return FieldAndValueAndParameters.withFieldName(mapping.columnName())
.withValuePhrase("null") //$NON-NLS-1$
.buildOptional();
return buildNullFragment(mapping);
}

@Override
Expand All @@ -63,6 +62,12 @@ public <T> Optional<FieldAndValueAndParameters> visit(ValueMapping<T> mapping) {
return buildValueFragment(mapping, mapping.value());
}

@Override
public <T> Optional<FieldAndValueAndParameters> visit(ValueOrNullMapping<T> mapping) {
return mapping.value().map(v -> buildValueFragment(mapping, v))
.orElseGet(() -> buildNullFragment(mapping));
}

@Override
public <T> Optional<FieldAndValueAndParameters> visit(ValueWhenPresentMapping<T> mapping) {
return mapping.value().flatMap(v -> buildValueFragment(mapping, v));
Expand All @@ -73,6 +78,12 @@ private Optional<FieldAndValueAndParameters> buildValueFragment(AbstractColumnMa
return buildFragment(mapping, value);
}

private Optional<FieldAndValueAndParameters> buildNullFragment(AbstractColumnMapping mapping) {
return FieldAndValueAndParameters.withFieldName(mapping.columnName())
.withValuePhrase("null") //$NON-NLS-1$
.buildOptional();
}

private Optional<FieldAndValueAndParameters> buildFragment(AbstractColumnMapping mapping, Object value) {
String mapKey = RenderingStrategy.formatParameterMapKey(sequence);

Expand Down
12 changes: 11 additions & 1 deletion src/main/java/org/mybatis/dynamic/sql/update/UpdateDSL.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 the original author or authors.
* Copyright 2016-2021 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.
Expand Down Expand Up @@ -34,6 +34,7 @@
import org.mybatis.dynamic.sql.util.SelectMapping;
import org.mybatis.dynamic.sql.util.StringConstantMapping;
import org.mybatis.dynamic.sql.util.ValueMapping;
import org.mybatis.dynamic.sql.util.ValueOrNullMapping;
import org.mybatis.dynamic.sql.util.ValueWhenPresentMapping;
import org.mybatis.dynamic.sql.where.AbstractWhereDSL;
import org.mybatis.dynamic.sql.where.AbstractWhereSupport;
Expand Down Expand Up @@ -126,6 +127,15 @@ public UpdateDSL<R> equalTo(BasicColumn rightColumn) {
return UpdateDSL.this;
}

public UpdateDSL<R> equalToOrNull(T value) {
return equalToOrNull(() -> value);
}

public UpdateDSL<R> equalToOrNull(Supplier<T> valueSupplier) {
columnMappings.add(ValueOrNullMapping.of(column, valueSupplier));
return UpdateDSL.this;
}

public UpdateDSL<R> equalToWhenPresent(T value) {
return equalToWhenPresent(() -> value);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 the original author or authors.
* Copyright 2016-2021 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.
Expand Down Expand Up @@ -33,6 +33,7 @@
import org.mybatis.dynamic.sql.util.StringConstantMapping;
import org.mybatis.dynamic.sql.util.UpdateMappingVisitor;
import org.mybatis.dynamic.sql.util.ValueMapping;
import org.mybatis.dynamic.sql.util.ValueOrNullMapping;
import org.mybatis.dynamic.sql.util.ValueWhenPresentMapping;

public class SetPhraseVisitor extends UpdateMappingVisitor<Optional<FragmentAndParameters>> {
Expand Down Expand Up @@ -74,6 +75,16 @@ public <T> Optional<FragmentAndParameters> visit(ValueMapping<T> mapping) {
return buildFragment(mapping, mapping.value());
}

@Override
public <T> Optional<FragmentAndParameters> visit(ValueOrNullMapping<T> mapping) {
return mapping.value()
.map(v -> buildFragment(mapping, v))
.orElseGet(() -> FragmentAndParameters
.withFragment(mapping.columnName() + " = null") //$NON-NLS-1$
.buildOptional()
);
}

@Override
public <T> Optional<FragmentAndParameters> visit(ValueWhenPresentMapping<T> mapping) {
return mapping.value().flatMap(v -> buildFragment(mapping, v));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 the original author or authors.
* Copyright 2016-2021 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.
Expand Down Expand Up @@ -38,6 +38,8 @@ public interface ColumnMappingVisitor<R> {

<T> R visit(ValueMapping<T> mapping);

<T> R visit(ValueOrNullMapping<T> mapping);

<T> R visit(ValueWhenPresentMapping<T> mapping);

R visit(SelectMapping mapping);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 the original author or authors.
* Copyright 2016-2021 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.
Expand All @@ -21,6 +21,11 @@ public final <T> R visit(ValueMapping<T> mapping) {
throw new UnsupportedOperationException();
}

@Override
public final <T> R visit(ValueOrNullMapping<T> mapping) {
throw new UnsupportedOperationException();
}

@Override
public final <T> R visit(ValueWhenPresentMapping<T> mapping) {
throw new UnsupportedOperationException();
Expand Down
48 changes: 48 additions & 0 deletions src/main/java/org/mybatis/dynamic/sql/util/ValueOrNullMapping.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright 2016-2021 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
*
* http://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.mybatis.dynamic.sql.util;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

import org.mybatis.dynamic.sql.SqlColumn;

public class ValueOrNullMapping<T> extends AbstractColumnMapping {

private final Supplier<T> valueSupplier;
// keep a reference to the column so we don't lose the type
private final SqlColumn<T> localColumn;

private ValueOrNullMapping(SqlColumn<T> column, Supplier<T> valueSupplier) {
super(column);
this.valueSupplier = Objects.requireNonNull(valueSupplier);
localColumn = Objects.requireNonNull(column);
}

public Optional<Object> value() {
return Optional.ofNullable(localColumn.convertParameterType(valueSupplier.get()));
}

@Override
public <R> R accept(ColumnMappingVisitor<R> visitor) {
return visitor.visit(this);
}

public static <T> ValueOrNullMapping<T> of(SqlColumn<T> column, Supplier<T> valueSupplier) {
return new ValueOrNullMapping<>(column, valueSupplier);
}
}
95 changes: 95 additions & 0 deletions src/test/java/examples/animal/data/AnimalDataTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -1406,6 +1406,46 @@ void testUpdate() {
}
}

@Test
void testUpdateValueOrNullWithValue() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
AnimalDataMapper mapper = sqlSession.getMapper(AnimalDataMapper.class);
AnimalData record = new AnimalData();
record.setBodyWeight(2.6);

UpdateStatementProvider updateStatement = update(animalData)
.set(animalName).equalToOrNull("fred")
.where(id, isEqualTo(1))
.build()
.render(RenderingStrategies.MYBATIS3);

assertThat(updateStatement.getUpdateStatement()).isEqualTo(
"update AnimalData set animal_name = #{parameters.p1,jdbcType=VARCHAR} where id = #{parameters.p2,jdbcType=INTEGER}");
int rows = mapper.update(updateStatement);
assertThat(rows).isEqualTo(1);
}
}

@Test
void testUpdateValueOrNullWithNull() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
AnimalDataMapper mapper = sqlSession.getMapper(AnimalDataMapper.class);
AnimalData record = new AnimalData();
record.setBodyWeight(2.6);

UpdateStatementProvider updateStatement = update(animalData)
.set(animalName).equalToOrNull((String) null)
.where(id, isEqualTo(1))
.build()
.render(RenderingStrategies.MYBATIS3);

assertThat(updateStatement.getUpdateStatement()).isEqualTo(
"update AnimalData set animal_name = null where id = #{parameters.p1,jdbcType=INTEGER}");
int rows = mapper.update(updateStatement);
assertThat(rows).isEqualTo(1);
}
}

@Test
void testInsert() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Expand Down Expand Up @@ -1994,6 +2034,61 @@ void testGeneralInsert() {
}
}

@Test
void testGeneralInsertValueOrNullWithValue() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
AnimalDataMapper mapper = sqlSession.getMapper(AnimalDataMapper.class);

GeneralInsertStatementProvider insertStatement = insertInto(animalData)
.set(id).toValue(101)
.set(animalName).toValueOrNull("Fred")
.set(brainWeight).toConstant("2.2")
.set(bodyWeight).toValue(4.5)
.build()
.render(RenderingStrategies.MYBATIS3);

String expected = "insert into AnimalData (id, animal_name, brain_weight, body_weight) "
+ "values (#{parameters.p1,jdbcType=INTEGER}, #{parameters.p2,jdbcType=VARCHAR}, 2.2, "
+ "#{parameters.p3,jdbcType=DOUBLE})";

assertThat(insertStatement.getInsertStatement()).isEqualTo(expected);
assertThat(insertStatement.getParameters()).hasSize(3);
assertThat(insertStatement.getParameters()).containsEntry("p1", 101);
assertThat(insertStatement.getParameters()).containsEntry("p2", "Fred");
assertThat(insertStatement.getParameters()).containsEntry("p3", 4.5);

int rows = mapper.generalInsert(insertStatement);
assertThat(rows).isEqualTo(1);
}
}

@Test
void testGeneralInsertValueOrNullWithNull() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
AnimalDataMapper mapper = sqlSession.getMapper(AnimalDataMapper.class);

GeneralInsertStatementProvider insertStatement = insertInto(animalData)
.set(id).toValue(101)
.set(animalName).toValueOrNull((String) null)
.set(brainWeight).toConstant("2.2")
.set(bodyWeight).toValue(4.5)
.build()
.render(RenderingStrategies.MYBATIS3);

String expected = "insert into AnimalData (id, animal_name, brain_weight, body_weight) "
+ "values (#{parameters.p1,jdbcType=INTEGER}, null, 2.2, "
+ "#{parameters.p2,jdbcType=DOUBLE})";

assertThat(insertStatement.getInsertStatement()).isEqualTo(expected);
assertThat(insertStatement.getParameters()).hasSize(2);
assertThat(insertStatement.getParameters()).containsEntry("p1", 101);
assertThat(insertStatement.getParameters()).containsEntry("p2", 4.5);

int rows = mapper.generalInsert(insertStatement);
assertThat(rows).isEqualTo(1);
}
}

@Test
void testUpdateWithSelect() {
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
Expand Down
Loading