Skip to content

Instantly share code, notes, and snippets.

@bastienapp
Last active July 12, 2023 14:23
Show Gist options
  • Save bastienapp/592662fb51f7731a1d93ca6b0c11bd34 to your computer and use it in GitHub Desktop.
Save bastienapp/592662fb51f7731a1d93ca6b0c11bd34 to your computer and use it in GitHub Desktop.
import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public final class BeanUtils
extends org.springframework.beans.BeanUtils {
private BeanUtils() {
}
public static void copyNonNullProperties(
Object source, Object target
) {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
for (PropertyDescriptor targetPd : targetPds) {
if (targetPd.getWriteMethod() != null) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (
sourcePd != null
&& sourcePd.getReadMethod() != null
) {
try {
Method readMethod = sourcePd.getReadMethod();
if (
!Modifier.isPublic(
readMethod.getDeclaringClass()
.getModifiers())
) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
// Ignore properties with null values.
if (value != null) {
Method writeMethod = targetPd.getWriteMethod();
if (
!Modifier.isPublic(
writeMethod.getDeclaringClass()
.getModifiers())
) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
} catch (Throwable ex) {
throw new FatalBeanException(
"Could not copy properties from source to target", ex
);
}
}
}
}
}
}
import com.example.wildmovies.entity.Movie;
import com.example.wildmovies.repository.MovieRepository;
import com.example.wildmovies.utils.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.UUID;
@RestController
@RequestMapping("/api/movies")
public class MovieController {
private final MovieRepository movieRepository;
public MovieController(MovieRepository movieRepositoryInjected) {
this.movieRepository = movieRepositoryInjected;
}
@PutMapping("/{id}")
public Movie update(@PathVariable UUID id, @RequestBody Movie movieUpdate) {
Movie movie = this.movieRepository
.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
BeanUtils.copyNonNullProperties(movieUpdate, movie);
return this.movieRepository.save(movie);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment