시그마 삽질==six 시그마

ObjectMapper & OrikaMapper basic 본문

프로그래밍/Spring

ObjectMapper & OrikaMapper basic

Ethan Matthew Hunt 2020. 8. 24. 21:35

 

1. Entity & DTO

 

//setter는 잘 안쓰지만 테스트용도로....

package study.querydsl.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;

import javax.persistence.*;

@Entity
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@ToString(of = {"id", "username", "age"})
public class Member {
    @Id
    @GeneratedValue
    @Column(name = "member_id")
    private Long id;
    private String username;
    private int age;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "team_id")
    private Team team;

    public Member(String username) {
        this(username, 0);
    }

    public Member(String username, int age) {
        this(username, age, null);
    }

    public Member(String username, int age, Team team) {
        this.username = username;
        this.age = age;
        if (team != null) {
            changeTeam(team);
        }
    }

    public void changeTeam(Team team) {
        this.team = team;
        team.getMembers().add(this);
    }
}




@Entity
@Getter
@Setter
@NoArgsConstructor(access = AccessLevel.PROTECTED)

@ToString(of = {"id", "name"})
public class Team {
    @Id
    @GeneratedValue
    @Column(name = "team_id") private Long id;
    private String name;

    @JsonIgnore
    //@Fetch(FetchMode.SUBSELECT)
    @BatchSize(size = 10)
    @OneToMany(mappedBy = "team")
    List<Member> members = new ArrayList<>();
    public Team(String name) { this.name = name;
    } 
}


@Data
public class MemberDto {
    private String username;
    private int age;
    private Team team;
    public MemberDto() {
    }
    @QueryProjection
    public MemberDto(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public MemberDto(String username, int age, Team team) {
        this.username = username;
        this.age = age;
        this.team = team;
    }
}

 

 

 

2. ObjectMapper

Object <--->JsonString 변환시  많이 사용하는 라이브러리

 

	// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
	implementation'com.fasterxml.jackson.core:jackson-databind:2.11.0'

 

    @Test
    public void objectMapperTest() throws Exception{

        ObjectMapper mapper = new ObjectMapper();

        Team teamA = new Team("teamA");
        em.persist(teamA);

        Member member1 = new Member("member1", 10, teamA);
        Member member2 = new Member("member2", 20, teamA);
        em.persist(member1);
        em.persist(member2);


        ////Convert object to JSON
        String jsonString = mapper.writeValueAsString(teamA);

        System.out.println("jsonString = " + jsonString);
        //결과 : jsonString = {"id":1,"name":"teamA","members":[{"id":2,"username":"member1","age":10},{"id":3,"username":"member2","age":20}]}



        //Convert object to JSON string and pretty print
        String prettyJsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(teamA);
        System.out.println("prettyJsonString = " + prettyJsonString);
        /*결과 :
        prettyJsonString = {
          "id" : 1,
          "name" : "teamA",
          "members" : [ {
            "id" : 2,
            "username" : "member1",
            "age" : 10
          }, {
            "id" : 3,
            "username" : "member2",
            "age" : 20
          } ]
        }
         */


        // Convert JSON string to Object

        String jsonInString ="{\"id\":1,\"name\":\"teamA\",\"members\":[{\"id\":2,\"username\":\"member1\",\"age\":10},{\"id\":3,\"username\":\"member2\",\"age\":20}]}";
        Team team = mapper.readValue(jsonInString, Team.class);
        System.out.println("team = " + team);
        //결과 : team = Team(id=1, name=teamA)



        //jsonString to map
        
        Map<String, String> map = mapper.readValue(jsonInString, Map.class);
        //Map map = mapper.readValue(jsonInString, new TypeReference<Map<Object, Object>>(){});
        System.out.println("map = " + map);
        //결과 : map = {id=1, name=teamA, members=[{id=2, username=member1, age=10}, {id=3, username=member2, age=20}]}
    }

 

 

3. Orika Mapper

 

Orika는 A를 B로 쉽게 매핑해주는 라이브러리임. 보통 Entity를 DTO로 변환할때 많이 사용함

 

 

https://orika-mapper.github.io/orika-docs/index.html

 

Orika reference guide

Orika simpler, lighter and faster Java bean mapping User Guide Important! This guide is (like Orika) a work in progress; any feedback in the way of suggestions or questions or problems can be posted to our project issues site, currently hosted at Google Co

orika-mapper.github.io

	// https://mvnrepository.com/artifact/ma.glasnost.orika/orika-core
	compile group: 'ma.glasnost.orika', name: 'orika-core', version: '1.5.4'

 

 @Test
    public void orikaMapperTest() throws Exception{

        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().mapNulls(true).build();
        MapperFacade mapper = mapperFactory.getMapperFacade();

        Team teamA = new Team("teamA");
        em.persist(teamA);

        Member member = new Member("", 10, teamA);
        em.persist(member);

		//Member Entity를 DTO에 매핑시킴
        MemberDto map = mapper.map(member, MemberDto.class);
        System.out.println("map = " + map);

        //결과: map = MemberDto(username=, age=10, team=Team(id=1, name=teamA))

        Member member3 = new Member("member3", 20);
        em.persist(member3);
        MemberDto map3 = mapper.map(member3, MemberDto.class);

        System.out.println("map3 = " + map3);
        //결과 : map3 = MemberDto(username=member3, age=20, team=null)
    }

'프로그래밍 > Spring' 카테고리의 다른 글

Spring webflux  (0) 2022.07.19
Spring batch 요약  (0) 2020.10.25
@TransactionalEventListener  (0) 2020.10.22
Spring Cloud Netflix  (0) 2020.10.18
Spring Kafka Basic  (0) 2020.08.25
Comments