1

I am facing problem regarding creating dynamic attributes with different data types (int, boolean, float, double, long, String, byte, ...) in Java using Spring Boot REST API and store in MongoDB collection. How can I get a solution for this?

@Field(value = "attributes")
Map<String, Object> attributes = new LinkedHashMap<>();

/*
 * setter for map attributes
 */
@JsonAnySetter
public void setAttributes(String key, Object value) {

    Set<Map.Entry<String, Object>> s = attributes.entrySet();

    for (Map.Entry<String, Object> it : s) {
        key = it.getKey();
        value = it.getValue();
        this.attributes.put(key, value);
    }
}

I am using this one but it's storing all data types as String only. I need not require to store any value only I need to store attributes for particular data types.

1 Answer 1

1

I don't understand exactly why your solution doesn't work. Try next:

Specify some class with your attributes:

import java.util.Map;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class User {
private Map<String, Object> attributes;

public User(Map<String, Object> attributes) {
    this.attributes = attributes;
}

public Object getAttribute() {
    return this.attributes;
}}

Specify mongodb repository:

interface UserRepository extends MongoRepository<User, UUID> {}

Controller to save dummy User:

@RestController
public class DemoController {

@Autowired
UserRepository userRepository;

@GetMapping("/save")
public User doSave() {
    Map<String, Object> attributes = new HashMap<>();

    attributes.put("time", Instant.now());
    attributes.put("num", 5.6);
    attributes.put("str", "5.6");

    return userRepository.save(new User(attributes));
}
}

I got the next response:

{
"attribute": {
    "str": "5.6",
    "num": 5.6,
    "time": "2019-07-24T12:22:07.390Z"
}
}

The object in MongoDB:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.