
Criteria Builderを使い下記の要領でDBのレコードをlike検索をしたいです。
ビューからの入力が2018-07-02であればDBから18-07-02に前方一致するレコードを取得。 ・ビューからの入力(String) 2018-07-02 ・ヒットするデータ(Timestamp) 18-07-02 xx:xx:xx.xxxxxxxxx 18-07-02 yy:yy:yy.yyyyyyyyy ・ ・
下記プログラムを組みましたが
実行時にエラーが発生します。
Parameter value
[2018-07-02%] did not match expected type [java.util.Date (n/a)]
試しにエンティティクラスでフィールドの型をDate→Stringに変更してみると
問題なく動作しました。
APIの使い方が間違っているのでしょうか。
リポジトリ
public interface CommandHistoryRepository extends JpaRepository<CommandHistory, Long>, JpaSpecificationExecutor<CommandHistory> { }
サービス
@Service public class CommandHistoryService { @Autowired private CommandHistoryRepository historyRepository; public List<CommandHistory> findBySpecification(SpecificationBuilder builder) { Specifications<CommandHistory> whereClause = builder.build(); return historyRepository.findAll(whereClause, new Sort(Direction.ASC, "id")); }
Specificationビルダー(ここでlike検索をしています)
public class SpecificationBuilder { private Specification<CommandHistory> startDateSpec; /** * @param argStartDate String型の日付(YYYY-MM-dd) * @return フィールドのstartDateSpecにlike検索が設定された自身のオブジェクト */ public SpecificationBuilder startDate(String argStartDate) { startDateSpec = (StringUtils.isEmpty(argStartDate) ? null : (root, query, cb) -> { return cb.like(root.get("startDate"), argStartDate.substring(2) + "%"); }); return this; } public Specifications<CommandHistory> build() { Specifications<CommandHistory> where = Specifications.where(startDateSpec) return where; }
コントローラ
@Autowired private CommandHistoryService commandHistoryService; @RequestMapping(value = "/list/history", params = "search", method = GET) public ModelAndView QueryResult(@RequestParam Map<String, String> param) { //クエリ発行 List<CommandHistory> history = commandHistoryService.findBySpecification (new CommandHistorySpecificationBuilder() //start-dateは必ずYY-MM-ddで入力されます .startDate(param.get("startDate")));
エンティティクラス(一部割愛)
import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "CommandHistory") public class CommandHistory { /** 内部管理用のID */ @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "commandhistory_seq") @SequenceGenerator(name = "commandhistory_seq", sequenceName = "commandhistory_seq", allocationSize = 1) @Column(name = "id") private Long id; @Column(name = "start_date") @Temporal(TemporalType.TIMESTAMP) private Date startDate;
Oracle DB定義
ID NOT NULL NUMBER(19) ・ ・ START_DATE TIMESTAMP(6)
Stack Overflowでも探してみましたがTimestamp型をlike検索する事例がなかったので
見つけることが出来ませんでした。
ご存知の方、どうぞご教授ください。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/07/03 06:58