michaellavelle / spring-data-dynamodb

Simplifies the development of creating an Amazon DynamoDB-based Java data access layer
https://derjust.github.io/spring-data-dynamodb/
Apache License 2.0
169 stars 284 forks source link

data validation #24

Closed jAddict7 closed 9 years ago

jAddict7 commented 10 years ago

How to add validation to the bean fields before CRUD performs?

michaellavelle commented 10 years ago

Hi I've now added initial support for JSR-303 Validation. To use this feature, you'll need to create a DynamoDBTemplate bean in your application config, and configure @EnableDynamoDBRepositories to reference this bean instead of using the AmazonDynamoDB client directly as in previous versions.

One you've made this change, adding a ValidatingDynamoDBEventListener bean to your application context ( wiring in your LocalValidatorFactoryBean ) should add the support for data validation you need.

I've modified the spring-data-dynamodb-demo project to enable this validation - should be useful as a reference.

Hope this helps,

Michael

jAddict7 commented 10 years ago

@Configuration @EnableWebMvc @ComponentScan("repositorypkg") @EnableDynamoDBRepositories(basePackages = "repositorypkg", dynamoDBOperationsRef="dynamoDBOperations") @PropertySources(value = {@PropertySource("classpath:/environment.properties")}) public class AppConfig {

@Autowired
private Environment env;

@Bean
public AmazonDynamoDB amazonDynamoDB() {
    AmazonDynamoDB amazonDynamoDB = new AmazonDynamoDBClient(
            amazonAWSCredentials());
    if (StringUtils.isNotEmpty(env.getRequiredProperty("amazon.dynamodb.endpoint"))) {
        amazonDynamoDB.setEndpoint(env.getRequiredProperty("amazon.dynamodb.endpoint"));
    }
    return amazonDynamoDB;
}

@Bean public DynamoDBOperations dynamoDBOperations(){
    return new DynamoDBTemplate(amazonDynamoDB());
}

@Bean public LocalValidatorFactoryBean validator(){
    return new LocalValidatorFactoryBean();
}

@Bean public ValidatingDynamoDBEventListener validatingDynamoDBEventListener(){
    return new ValidatingDynamoDBEventListener(validator());
}

@Bean
public AWSCredentials amazonAWSCredentials() {
    return new BasicAWSCredentials(env.getRequiredProperty("amazon.aws.accesskey"), env.getRequiredProperty("amazon.aws.secretkey"));
}

}

And I have used @NotNull to a domain variable still it allows entry of null object?

michaellavelle commented 10 years ago

I'm not able to reproduce this I'm afraid, @NotNull validation works in all the testing I've done.

I just checked out the spring-data-dynamodb-demo project, added @NotNull to the category attribute of the Forum domain object, and if I try to insert a Forum instance with null category, I get a ConstraintViolationException thrown as is the expected behaviour.

Could you try the same test, and if this also works correctly for you, perhapss you could try your domain object in the demo and see if the validation works there?