Skip to content

DATAJDBC-182 - Support modifying query on the query method #48

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

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2018 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.springframework.data.jdbc.repository.query;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
* Indicates a method should be regarded as modifying query.
*
* @author Kazuki Shimizu
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Documented
public @interface Modifying {
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,17 @@ public RepositoryQuery resolveQuery(Method method, RepositoryMetadata repository

JdbcQueryMethod queryMethod = new JdbcQueryMethod(method, repositoryMetadata, projectionFactory);
Class<?> returnedObjectType = queryMethod.getReturnedObjectType();
RowMapper<?> rowMapper = context.getSimpleTypeHolder().isSimpleType(returnedObjectType)
? SingleColumnRowMapper.newInstance(returnedObjectType, conversionService)
: new EntityRowMapper<>( //
context.getRequiredPersistentEntity(returnedObjectType), //
conversionService, //
context, //
accessStrategy //
);

RowMapper<?> rowMapper = null;
if (!queryMethod.isModifyingQuery()) {
rowMapper = context.getSimpleTypeHolder().isSimpleType(returnedObjectType)
? SingleColumnRowMapper.newInstance(returnedObjectType, conversionService)
: new EntityRowMapper<>( //
context.getRequiredPersistentEntity(returnedObjectType), //
conversionService, //
context, //
accessStrategy //
);
}
return new JdbcRepositoryQuery(queryMethod, context, rowMapper);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
import java.lang.reflect.Method;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.data.repository.core.RepositoryMetadata;
Expand All @@ -30,6 +32,7 @@
* Binds method arguments to named parameters in the SQL statement.
*
* @author Jens Schauder
* @author Kazuki Shimizu
*/
public class JdbcQueryMethod extends QueryMethod {

Expand All @@ -47,4 +50,15 @@ public String getAnnotatedQuery() {

return queryAnnotation == null ? null : queryAnnotation.value();
}

/**
* Returns whether the query method is a modifying one.
*
* @return if it's a modifying query, return {@code true}.
*/
@Override
public boolean isModifyingQuery() {
return AnnotationUtils.findAnnotation(method, Modifying.class) != null;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,20 @@ public Object execute(Object[] objects) {
parameters.addValue(parameterName, objects[p.getIndex()]);
});

if (queryMethod.isModifyingQuery()) {
int updatedCount = context.getTemplate().update(query, parameters);
Class<?> returnedObjectType = queryMethod.getReturnedObjectType();
return (returnedObjectType == boolean.class || returnedObjectType == Boolean.class) ? updatedCount != 0 : updatedCount;
}

if (queryMethod.isCollectionQuery() || queryMethod.isStreamQuery()) {
return context.getTemplate().query(query, parameters, rowMapper);
} else {
}

try {
return context.getTemplate().queryForObject(query, parameters, rowMapper);
} catch (EmptyResultDataAccessException e) {
return null;
}
try {
return context.getTemplate().queryForObject(query, parameters, rowMapper);
} catch (EmptyResultDataAccessException e) {
return null;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,39 @@ public void executeCustomQueryWithReturnTypeIsLocalDateTimeList() {

}

@Test // DATAJDBC-182
public void executeCustomModifyingQueryWithReturnTypeIsNumber() {

DummyEntity entity = dummyEntity("a");
repository.save(entity);

assertThat(repository.updateName(entity.id, "b")).isEqualTo(1);
assertThat(repository.updateName(9999L, "b")).isEqualTo(0);
assertThat(repository.findById(entity.id)).isPresent().map(e -> e.name).contains("b");

}

@Test // DATAJDBC-182
public void executeCustomModifyingQueryWithReturnTypeIsBoolean() {

DummyEntity entity = dummyEntity("a");
repository.save(entity);

assertThat(repository.deleteByName("a")).isTrue();
assertThat(repository.deleteByName("b")).isFalse();
assertThat(repository.findById(entity.id)).isNotPresent();

}

@Test // DATAJDBC-182
public void executeCustomModifyingQueryWithReturnTypeIsVoid() {

repository.insert("Spring Data JDBC");

assertThat(repository.findByNameAsEntity("Spring Data JDBC")).isNotNull();

}

private DummyEntity dummyEntity(String name) {

DummyEntity entity = new DummyEntity();
Expand Down Expand Up @@ -265,5 +298,17 @@ private interface DummyEntityRepository extends CrudRepository<DummyEntity, Long
@Query("VALUES (current_timestamp),(current_timestamp)")
List<LocalDateTime> nowWithLocalDateTimeList();

@Modifying
@Query("UPDATE DUMMYENTITY SET name = :name WHERE id = :id")
int updateName(@Param("id") Long id, @Param("name") String name);

@Modifying
@Query("DELETE FROM DUMMYENTITY WHERE name = :name")
boolean deleteByName(@Param("name") String name);

@Modifying
@Query("INSERT INTO DUMMYENTITY (name) VALUES(:name)")
void insert(@Param("name") String name);

}
}