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
);