Mapping JSON to Entity
Let’s say that you have a json file which you want to map to a table in the database in your application with Spring Boot
First, in order to map this to a class, we need to create an entity.
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.validation.constraints.Size;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Language {
@Id
@Size(min = 3, max = 3)
private String languageCode;
private String languageName;public Language(String languageCode) {
super();
this.languageCode = languageCode;
}
All annotations except for Entity above class definition comes from Lombok library. Data annotation provides getters, setters, equals function, the other two is pretty self-explanatory. If you decide to use Lombok in your project and have problems, I suggest you to take a look at this post.
I wanted to use language code field as the primary key, since it’s internationally accepted and unique for each spoken language. You can also have a Long field and let javax.persistence library to auto generate an id for you, it is entirely up to your design choices.
After that, I created a command line runner to load this json into my database at the beginning of the application.
package com.countries.mehmet;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.countries.mehmet.domain.Language;
import com.countries.mehmet.service.ILanguageService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;import java.io.InputStream;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;@Component
public class LanguagesCommandLineRunner implements CommandLineRunner {private static final Logger log =
LoggerFactory.getLogger(LanguagesCommandLineRunner.class);
@Autowired
private ILanguageService languageService;
@Override
public void run(String... args) throws Exception {
loadLanguages();
}
private void loadLanguages() {
ObjectMapper mapper = new ObjectMapper();
TypeReference<List<Language>> typeReference = new TypeReference<List<Language>>(){};
InputStream inputStream = TypeReference.class.getResourceAsStream("/json/languages.json");
try {
List<Language> languages = mapper.readValue(inputStream, typeReference);
languageService.save(languages);
log.info(String.format("%d languages saved to H2 database", languages.size()));
} catch (Exception e) {
log.error("Failed to save languages to db :" + e.getMessage());
}
}}
CommandLineRunner interface have one abstract method that needs to be implemented, i.e. run.
import java.util.Iterator;import java.util.List;import com.countries.mehmet.domain.Language;public interface ILanguageService { List<Language> list(); Iterator<Language> save(List<Language> languages); Language findById(String id);}
Language service is an interface which needs to be implemented in order to connect to your database in the back. While implementing, I used JPA repository and an H2 in-memory database.