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】DBから取得したListをLocalDateTimeでソートする

Last updated at Posted at 2026-01-05

やりたいこと

  1. mybatisでSQLを実行
  2. Listで戻り値を取得
  3. 取得した戻り値を、javaで更新日時の降順(最新順)にソート
  4. 最新の1レコードを取得する

やったこと

1.mybatisで以下SQLを実行

sampleMapper.xml
<select id="sampleSql" parameterType="String" resultType="sample.hoge.sampleSqlResDto">
    SELECT
        id,
        name,
        update_date
    FROM
        sample_table
    WHERE
        name = #{paramName, jdbcType=VARCHAR}
</select>

2.Listで戻り値を取得

sampleMapper.java
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface SampleMapper {

    List<sampleSqlResDto> sampleSql(
        @Param("paramName") String paramName
    );
}
sampleSqlResDto.java
import lombok.Data;
import java.time.LocalDateTime;

@Data
public class sampleSqlResDto {
    private int id;
    private String name;
    private LocalDateTime updateDate;
}

3.取得した戻り値を、javaで更新日時の降順(最新順)にソート
4.最新の1レコードを取得する

sampleService.java
// 中略

List<sampleSqlResDto> nekoList = mapper.sampleSql("neko");
nekoList.sort(Comparator.comparing(sampleSqlResDto::getUpdateDate).reversed());

// 更新日時が最新のレコードを取得する
latestNeko = nekoList.get(0);

注意点

  • リストの順序を直接変更しているので、リスト自体も使用する場合は別の方法が良い
  • 昇順(古い順)にする場合は.reversed()は不要
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?