среда, 3 сентября 2014 г.

Spring Data MongoDB

Если при попытке вставить документ в коллекцию ничего не происходит или возникает OptimisticalLockException (при том, что очевидных поводов для этого исключения не наблюдается) советую проверить индексы коллекции. Особенно если индексы используются для геолокации.

К примеру есть у нас такой репозиторий:
@Component
public class TestRepository extends BaseRepository<TestEntity> {
 @PostConstruct
    public void init() {
        ensureGeoIndex("testField");
    }
}
наследуется от такого класса:
@Component
public class BaseRepository<T extends BaseEntity> {
@Autowired
protected MongoOperations op;
protected void ensureGeoIndex(String fieldName) {
        GeospatialIndex index = new GeospatialIndex(fieldName);
        IndexOperations indexOperations = op.indexOps(domainClass);
        indexOperations.ensureIndex(index);
    }
}
Если попытаться вставить запись вот так:
TestEntity testEntity=new TestEntity();testEntity.setTestField("testValue");testRepository.save(testEntity);
в базу ничего не запишется, т.к. монга ожидает в качестве значения примерно такую структуру:
{ type: "Point", coordinates: [ -1, 1 ] }

MongoDB

Удалить по дате создания
function objectIdWithTimestamp(timestamp)
{
    // Convert string date to Date object (otherwise assume timestamp is a date)
    if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }

    // Convert date object to hex seconds since Unix epoch
    var hexSeconds = Math.floor(timestamp/1000).toString(16);

    // Create an ObjectId with that hex timestamp
    var constructedObjectId = ObjectId(hexSeconds + "0000000000000000");

    return constructedObjectId
}
db.users.remove({ _id: { $gt: objectIdWithTimestamp('2014/07/15') } })

http://stackoverflow.com/questions/8749971/can-i-query-mongodb-objectid-by-date


Spring mvc jackson json serialization: null as empty string or ignore null

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;

@Configuration
public class JacksonSerializationConfig {

    @Bean
    public ObjectMapper jacksonObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        DefaultSerializerProvider sp = new DefaultSerializerProvider.Impl();
        sp.setNullValueSerializer(new NullSerializer());
        objectMapper.setSerializerProvider(sp);
        // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); //uncomment if need to ignore null strings
        return objectMapper;
    }

    @Bean
    public MappingJackson2HttpMessageConverter jackson2Converter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        converter.setObjectMapper(jacksonObjectMapper());
        return converter;
    }

    @Bean
    public SerializationConfig serializationConfig() {
        return jacksonObjectMapper().getSerializationConfig();
    }

    // and NullSerializer can be something as simple as:
    public class NullSerializer extends JsonSerializer<Object> {
        public void serialize(Object value, JsonGenerator jgen,
                              SerializerProvider provider)
                throws IOException, JsonProcessingException {
            // any JSON value you want...
            jgen.writeString("");
        }
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>