0

I am struggling with @DateTimeFormat I want only date to saved in Mongo so i am using @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) but when object get saved in mongo , it's saving 2016-12-17 09:30:19.795Z I am Using spring 4.1.1 and spring-data-mongodb 1.7.2 my module-context.xml is

<context:component-scan base-package="psl.service.core.agentanalytics.internal"/>

<jpa:repositories base-package="psl.service.core.agentanalytics.internal.repository"
                  repository-impl-postfix="DetectPostfixToken"
                  entity-manager-factory-ref="entityManagerFactory"/>

<bean name="/agentanalytics/public" parent="contextAwareServiceExporter"
      p:service-ref="agentAnalyticsServicePublicImpl"
      p:serviceInterface="psl.service.core.agentanalytics.api.AgentAnalyticsServicePublic"/>

<bean name="/agentanalytics/jobs/public" parent="contextAwareServiceExporter"
      p:service-ref="agentAnalyticsServiceJobsPublicImpl"
      p:serviceInterface="psl.service.core.agentanalytics.api.AgentAnalyticsServiceJobsPublic"/>

<tx:annotation-driven/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg ref="mongo"/>
    <constructor-arg name="databaseName" value="xyz"/>
</bean>
<bean class=
              "org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<mongo:repositories
        base-package="psl.service.core.agentanalytics.internal" mongo-template-ref="mongoTemplate"/>


<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
      p:entityManagerFactory-ref="entityManagerFactory"/>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
      p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter" p:persistenceUnitName="agentanalyticsPU">
    <property name="packagesToScan">
        <value>psl.service.core.agentanalytics.internal</value>
    </property>
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
    </property>
</bean>

<bean id="mapper" class="psl.shared.util.dozerextn.internal.DozerBeanMapperFactoryBean">
    <property name="mappingFiles">
        <list>
            <value>classpath:META-INF/spring/dozer-mapping.xml</value>
        </list>
    </property>
</bean>

and my mongo pojo is

import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.format.annotation.DateTimeFormat;
import psl.service.core.agentanalytics.api.AgentDataPoints;
import psl.shared.impl.entity.MongoKeyedEntity;

import java.io.Serializable;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by agent1 on 14/12/16.
 */

@CompoundIndex(name = "account_date_idx", def = "{'account' : 1, 'date' : 1}", unique = true)
@Document(collection = "agent_data_storage")
public class AgentDataStorage extends MongoKeyedEntity<String> implements Serializable {
    @Field
    private Long account;

    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    @Field()
    private Date date;

    @Field
    private Map<String, Integer> dataPoints = new HashMap<>();

    public AgentDataStorage(Long account) {
        this.account = account;
        this.date = new Date();
        for (AgentDataPoints dataPoint : EnumSet.allOf(AgentDataPoints.class)) {
            this.dataPoints.put(dataPoint.toString(), 0);
        }
    }

    public AgentDataStorage(String account) {
        this.account = Long.valueOf(account);
        for (AgentDataPoints dataPoint : EnumSet.allOf(AgentDataPoints.class)) {
            this.dataPoints.put(dataPoint.toString(), 0);
        }
    }

    public AgentDataStorage(Long account, Date date) {
        this.account = account;
        this.date = date;
        for (AgentDataPoints dataPoint : EnumSet.allOf(AgentDataPoints.class)) {
            this.dataPoints.put(dataPoint.toString(), 0);
        }
    }

    public AgentDataStorage(Long account, Date date, Map<String, Integer> dataPoints) {
        this.account = account;
        this.date = date;
        this.dataPoints = dataPoints;
    }

    public AgentDataStorage(String account, Date date) {
        this.account = Long.valueOf(account);
        this.date = date;
        for (AgentDataPoints dataPoint : EnumSet.allOf(AgentDataPoints.class)) {
            this.dataPoints.put(dataPoint.toString(), 0);
        }
    }

    public Long getAccount() {
        return account;
    }

    public void setAccount(Long account) {
        this.account = account;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Map<String, Integer> getDataPoints() {
        return dataPoints;
    }

    public void setDataPoints(Map<String, Integer> dataPoints) {
        this.dataPoints = dataPoints;
    }

    public void updateDataPoint(AgentDataPoints agentDataPoints, Integer value) {
        this.dataPoints.put(String.valueOf(agentDataPoints), value);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("AgentDataStorage{");
        sb.append("account=").append(account);
        sb.append(", date=").append(date);
        sb.append(", dataPoints=").append(dataPoints);
        sb.append('}');
        return sb.toString();
    }
}
Gaurav Agrawal
  • 909
  • 1
  • 10
  • 20
  • Are you trying to save date as a string value ? – s7vr Dec 17 '16 at 11:59
  • No i want to save it in Mongolia iso date format – Gaurav Agrawal Dec 17 '16 at 12:42
  • DateTimeFormat is used for formatting purpose and it has nothing to do with the actual date value that is stored in Db. The mongo db saves the date value from your entity object. The value you see in the shell doesn't know anything about your formatting. – s7vr Dec 17 '16 at 12:50
  • so if want to save only date not time ..What is best way – Gaurav Agrawal Dec 17 '16 at 12:56
  • There is no such type in mongodb The best you can do is set your time part to zero and save it. You will see something like this in DB 2016-12-17 00:00:00.000Z. – s7vr Dec 17 '16 at 13:17
  • A [64bit Int _is_ the best way of storing a date](https://docs.mongodb.com/manual/reference/bson-types/#document-bson-type-date). You need to understand the difference between storing your date and displaying it. If you absolutely want to have your date normalized, subtract the result of your date mod 86400000 (msecs of one day) from your date. That gives you 00:00:00.000 of the respective day. Just pray you do not want to change resolution later. – Markus W Mahlberg Dec 17 '16 at 16:17
  • @MarkusWMahlberg If i store date in String format "yyyy-MM-dd" . Will It create any problem ? – Gaurav Agrawal Dec 17 '16 at 16:25
  • Yes. None of MongoDB's date related functions will work, nor will TTL indices. Furthermore, that string would be 10 bytes. Quite some overhead when compared to a 64bit integer. I can not understand why you insist making your life more complicated than it needs to be. – Markus W Mahlberg Dec 17 '16 at 19:39
  • @MarkusWMahlberg as my need is exactly as given in this question(http://stackoverflow.com/questions/6764821/what-is-the-best-way-to-store-dates-in-mongodb/6776273#6776273) but for different purpose . In the last answer they suggested to store date as String . I need normalized date only . Is there any other way around what you suggested above . – Gaurav Agrawal Dec 17 '16 at 19:56
  • As said by me and Remon: store it as a native type and format the _output_ according to your needs. – Markus W Mahlberg Dec 17 '16 at 20:05

0 Answers0