Home > Enterprise >  How to get a map of object properties to table field names in Spring Data JDBC?
How to get a map of object properties to table field names in Spring Data JDBC?

Time:10-05

I have an annotated entity object with custom table and field names which i use with Spring Data JDBC (not JPA). Smth like:

@Data
@Table("custom_record_table")
public class Record {
    @Id
    @Column("id_field")
    Long id;
    String name;
    @Column("name_short")
    String shortName;
}

I'd like to get a map of properties to fields. Smth like:

{"id":"id_field","name":"name","shortName":"name_short"}

What's the proper way to get it?

CodePudding user response:

you want to convert your objects to JSON. they are different libraries for it. people prefer Jackson library the most

import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.ObjectWriter; 

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

CodePudding user response:

What if you create a static function inside Record?

@Data
@Table("custom_record_table")

public class Record 
{
    @Id
    @Column("id_field")
    Long id;
    String name;
    @Column("name_short")
    String shortName;

   static Map<String, String> getMap()
   {
       return Map.ofEntries  ( 
                 Map.entry("id", "id_field"),
                 Map.entry("name", "name"),
                 Map.entry("shortName","name_short")
              );
   }

  /* returning map would look like: 
     {"id":"id_field","name":"name","shortName":"name_short"} */
}

Note that this would get you a Map, in which you can retrieve the field values by the field keys you know.

map.get("id") will return id_field, and so on. This may be useful when you need to know which is the name that references the fields.

BUT, if you just want an String representation, even a JSON, it would be best to create a JSON from those fields.

Anyway, if I understood correctly, you want a Map object, so the first solution should do it.

  • Related