Added simple CascadeSave email for User

This commit is contained in:
alex-semenyuk 2015-08-23 20:46:34 +02:00
parent a3e8f9f60e
commit c9d5aff1ff
4 changed files with 28 additions and 4 deletions

View File

@ -5,6 +5,7 @@ import java.util.List;
import org.baeldung.converter.UserWriterConverter;
import org.baeldung.event.CascadeSaveMongoEventListener;
import org.baeldung.event.UserCascadeSaveMongoEventListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
@ -36,6 +37,11 @@ public class MongoConfig extends AbstractMongoConfiguration {
return "org.baeldung";
}
@Bean
public UserCascadeSaveMongoEventListener userCascadingMongoEventListener() {
return new UserCascadeSaveMongoEventListener();
}
@Bean
public CascadeSaveMongoEventListener cascadingMongoEventListener() {
return new CascadeSaveMongoEventListener();

View File

@ -8,10 +8,10 @@ import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.util.ReflectionUtils;
public class CascadeCallback implements ReflectionUtils.FieldCallback {
private Object source;
private MongoOperations mongoOperations;
public CascadeCallback(final Object source, final MongoOperations mongoOperations) {
this.source = source;
this.setMongoOperations(mongoOperations);

View File

@ -6,10 +6,10 @@ import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventLis
import org.springframework.util.ReflectionUtils;
public class CascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
@Autowired
private MongoOperations mongoOperations;
@Override
public void onBeforeConvert(final Object source) {
ReflectionUtils.doWithFields(source.getClass(), new CascadeCallback(source, mongoOperations));

View File

@ -0,0 +1,18 @@
package org.baeldung.event;
import org.baeldung.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
public class UserCascadeSaveMongoEventListener extends AbstractMongoEventListener<Object> {
@Autowired
private MongoOperations mongoOperations;
@Override
public void onBeforeConvert(final Object source) {
if (source instanceof User && ((User) source).getEmailAddress() != null) {
mongoOperations.save(((User) source).getEmailAddress());
}
}
}