728x90
반응형

저장은 Json으로 하고, 불러올 땐 Object로 불러오게끔 하는 Converter를 만들어보자.

CRUD가 필요하지 않은 단순 조회용 데이터면 Json으로 저장하는 방법 또한 괜찮다고 생각한다.

 

1. Json으로 저장하고 Object로 불러오는 법

@Entity
@NoArgsConstructor
@Getter
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Convert(converter = UserDataDtoConverter.class)
    @Column(columnDefinition = "json")
    @ColumnTransformer(write = "?::json")
    private UserDataDto userData;
}

 

@Data
@AllArgsConstructor
@NoArgsConstructor
public class userDataDto {

    private String name;
    private String id;

}

 

@Slf4j
public class UserDataDtoConverter implements AttributeConverter<userDataDto, String> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(userDataDto attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            log.error("fail to serialize as object into Json : {}", attribute, e);
            throw new IllegalArgumentException(e);
        }
    }

    @Override
    public userDataDto convertToEntityAttribute(String dbData) {
        try {
            return objectMapper.readValue(dbData, userDataDto.class);
        } catch (IOException e) {
            log.error("fail to deserialize as Json into Object : {}", dbData, e);
            throw new IllegalArgumentException(e);
        }
    }
}

 

2. Json으로 Object 저장하는 법

    @Column(nullable = false, columnDefinition = "jsonb")
    @Type(JsonBinaryType.class)
    private Map<KEPCORateCode, KRRatePlan> plan; // Price Plan

    @Column(nullable = false, columnDefinition = "jsonb")
    @Type(JsonBinaryType.class)
    private CommonPricePlan commonPlan;

 

3. String으로 저장하고, List<String>으로 불러오는 법

    @Convert(converter = StringListConverter.class)
    @Column(columnDefinition = "text")
    private List<String> content = new ArrayList<>();
@Converter
public class StringListConverter implements AttributeConverter<List<String>, String> {

    private final ObjectMapper mapper;

    public StringListConverter(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public String convertToDatabaseColumn(List<String> attribute) {
        try {
            return mapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> convertToEntityAttribute(String dbData) {
        try {
            return mapper.readValue(dbData, new TypeReference<List<String>>() {
            });
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}

 

4. String으로 저장하고 List<Object>로 불러오는 법

    @Convert(converter = LoadProfileConverter.class)
    // @Column(columnDefinition = "text")
    private List<Profile> profile;

 

@Slf4j
public class LoadProfileConverter implements AttributeConverter<List<Profile>, String> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<Profile> attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            log.error("fail to serialize as object into Json : {}", attribute, e);
            throw new IllegalArgumentException(e);
        }
    }

    @Override
    public List<Profile> convertToEntityAttribute(String dbData) {
        try {
            return objectMapper.readValue(dbData, new TypeReference<List<Profile>>() {
            });
        } catch (IOException e) {
            log.error("fail to deserialize as Json into Object : {}", dbData, e);
            throw new IllegalArgumentException(e);
        }
    }
}
728x90
반응형

+ Recent posts