1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【java】別DTOにある同じプロパティの値をコピーする

Last updated at Posted at 2026-01-07

やりたいこと

  1. Aテーブルからレコード取得
  2. Bテーブルからレコード取得
  3. AとBの値をCにコピー

やったこと

// DBからレコードを取得
ADto aRecord = mapper.getA();
BDto bRecord = mapper.getB();

CDto result = new CDto();
// ADtoとCDto、BDtoとCDtoのうち、重複したプロパティの値をコピーする
BeanUtils.copyProperties(aRecord, result);
BeanUtils.copyProperties(bRecord, result);

注意点

  • コピー対象はプロパティ(getXxx, setXxx)が一致するもののみ
  • 同じプロパティがない場合、例外は発生せず正常に処理される
  • コピーする件数が少ない場合はgetter, setterを使用した方が確実
  • 複数回同一のオブジェクトにコピーする場合、プロパティが重複していると後勝ちになる

取り上げているのはspringframeworkのメソッドです。
apacheの同名メソッドは引数がコピー先, コピー元で逆になっているので注意

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?