0
0

More than 3 years have passed since last update.

Java Tips

Last updated at Posted at 2021-09-06

Java Tips

Objectをjsonに変換

Gsonを使う。
https://github.com/google/gson

dependencies {
  implementation 'com.google.code.gson:gson:2.8.7'
}
SampleModel results = SampleModel.findAll();

Gson gson = new Gson();
System.out.println(gson.toJson(results));

// 出力結果
// [{"id":1,"name":"Sample001"}, {"id":2,"name":"Sample002"}, {"id":3,"name":"Sample003"}]

StreamAPIのmap

PHPでいうarray_map、rubyでいうmap
Java Stream APIをいまさら入門

/*
 * 以下のような値を持つModel
 * [{"id":1,"name":"Sample001"}, {"id":2,"name":"Sample002"}, {"id":3,"name":"Sample003"}]
 */
SampleModel model = SampleModel.findAll();

/*
 * map処理
 * SampleModelに@Getterが付与されている前提
 */
List results = model.stream()
    .map(elem -> elem.getName())
    .collect(Collectors.toList())

// 出力結果:["Sample001", "Sample002", "Sample003"]
System.out.println(results);

@TestでprivateメソッドのExceptionが発生するかをテストする方法

[JAVA] JPAで1対Nで中間テーブルのあるDBをModelに落とし込む

JPAのNo default constructor for entityエラーについて

JPAでlimit

// select * from samples order by id desc limit 3;
public List<SampleModel> findTop3ByOrderByIdDesc();

JPAでwhere != (not equal)

UserIdNot のようにカラム名の末尾にNotを付ける

/*
select
    *
from
    samples
where
    user_id != "xxxx"
and group_id = "xxxx"
order by
    id desc
limit 3;
*/
public List<SampleModel> findTop3ByUserIdNotAndGroupIdOrderByIdDesc(
    String userId,
    String groupId
);
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