0
0

ModelMapperでenumマッピングのデモ

Posted at

まず、enum Color定義します。

Color
enum Color {
	WHITE("白", "color is white"),
	BLACK("黒", "color is black");

	private String value;
	private String description;

	Color(String value, String description) {
		this.value = value;
		this.description = description;
	}

	public String getValue() {
		return value;
	}

	public String getDescription() {
		return description;
	}
}

Catを定義します。カラー属性がある。

Cat
class Cat {
	private Color color;

	public Cat() {
	}

	public Cat(Color color) {
		this.color = color;
	}

	public Color getColor() {
		return color;
	}

	public void setColor(Color color) {
		this.color = color;
	}
}

CatVOを定義します。ページにカラーを表示するには、この属性は文字列でなければならない。

CatVO
public class CatVO {
	private String color;

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}
}

ページに戻るとき、期待値 color=白

ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

Cat cat = new Cat(Color.WHITE);
// Cat → copy to → CatVO
CatVO catVO = mapper.map(cat, CatVO.class);

// 期待値 color=白, 実績値:color=WHITE
System.out.println(catVO.getColor());

2つの変換方法がある

方法1
mapper.typeMap(Cat.class, CatVO.class).addMappings(
				m -> m.using((Converter<Color, String>) context 
						-> context.getSource().getValue()).map(Cat::getColor, CatVO::setColor));
方法2:簡単
public class CatVO {
	private String color;

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

    // 追加して、自動的に呼び出すことができる。
	public void setColor(Color color) {
		this.color = color.getValue(); 
	}
}

どっちがいい? 他に何か良い方法はありますか?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0