Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format @param String in Spring Data Rest

I have to convert the incoming parameter value to Repository interface into desired format, is it possible to do it. My Domain Class,

@DynamoDBTable(tableName = "test")
public class Test implements Serializable{

    @Id
    private String id;
    private String name;
    private String date;

    @DynamoDBHashKey(attributeName = "id")
    @DynamoDBAutoGeneratedKey
    public String getId() {
        return id;
    }

    @DynamoDBAttribute(attributeName = "name")
    public String getName() {
        return name;
    }

    @DynamoDBAttribute(attributeName = "date")
    @JsonSerialize(using = StringDateSerializer.class)
    public String getDate() {
        return date;
    }
    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    @JsonDeserialize(using = StringDateDeserializer.class)
    public void setDate(String date) {
        this.date = date;
    }

}

And my repository interface,

@EnableScan
@RestResource(path="test", rel="test")
public interface TestRepository extends PagingAndSortingRepository<Test, String>{

    @RestResource(path="testsearch", rel="test")
    public Page<Test> findByNameAndDateLessThan(@Param("name") String name, @Param("date") String date, Pageable pageable);

}

Here I have to convert the incoming date String to time using getTime() method of Java. Is it possible to achieve this without using controller and am not interested in sending from client side because timezone problem may occur.

My Convertors:

public class StringDateSerializer extends JsonSerializer<String> {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

    @Override
    public void serialize(String time, JsonGenerator gen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        Date date = new Date(Long.parseLong(time));
        String formattedDate = dateFormat.format(date);
        gen.writeString(formattedDate);
    }

}

public class StringDateDeserializer extends JsonDeserializer<String> {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

    @Override
    public String deserialize(JsonParser parser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        String dateReceived = parser.getText();
        Date date = null;
        try {
            date = dateFormat.parse(dateReceived);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return String.valueOf(date.getTime());
    }

}

Here I have to use, GET /test/search/test?name=xx&date=14-06-2014. I need to get all the names with date less than 14-06-2014 and left the datas with or after 14-06-2014.

While POST and GET, I have converted the incoming and outgoing string using JsonSerialize and JsonDeserialize annotations but if I want to fetch any data using finder method its not converting as I thought.

For example, If I save {"name": "Test", "date": "08-10-2014"}, in DB it will be saved by its equivalent time and If I want to search it using 08-10-2014 not the time constant. I am new to springs and I cant find a way for it. Thanks in advance.

like image 257
jAddict Avatar asked May 09 '26 00:05

jAddict


1 Answers

What's the reason you use String as the type for the date in the first place. That's quite suboptimal (to phrase it politely) API design.

Spring Data REST support the usage of @DateTimeFormat on query method parameters to turn the String base representation you get from the HTTP request into a Date. So your repository interface might look something like this:

public interface TestRepository extends PagingAndSortingRepository<Test, String>{

  public Page<Test> findByNameAndDate(@Param("name") String name, 
    @Param("date") @DateTimeFormat(iso = ISO.DATE) Date date, Pageable pageable);
}

This will cause Strings like 2014-06-08 to be turned into the appropriate Date.

like image 188
Oliver Drotbohm Avatar answered May 10 '26 13:05

Oliver Drotbohm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!