実行環境
Java : version "1.8.0_172"
SpringBoot : spring-boot-gradle-plugin:2.0.5
MySQL : Ver 8.0.12 for osx10.13 on x86_64 (Homebrew)
実現したいこと
特定の年月のデータをデータベースから取得し、表示させたいです。
RepositoryクラスでQueryを使ってデータを取得しようとしたのですが、下記の実装だとList型になっていないせいか、エラーになってアプリが実行できません。
Repository
java
1@Repository 2public interface IncomeOutgoRepository extends JpaRepository<IncomeOutgo, Integer> { 3 @Query("select * from income_outgo where DATE_FORMAT(date,'%Y-%m') = :month") 4 List<IncomeOutgo> findByMonth(@Param("month") String month); 5}
エラーメッセージは以下になります。
: Application run failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'incomeOutgoController': Unsatisfied dependency expressed through field 'incomeOutgoService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'incomeOutgoService': Unsatisfied dependency expressed through field 'incomeOutgoRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'incomeOutgoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.Collection income_outgo.IncomeOutgoRepository.findByMonth(java.lang.String)!
最適な実装方針ありましたら、ご教示頂けますと幸いです。
よろしくお願いいたします。
Serviceクラス、Controllerクラスの実装は以下の通りです。
Service
java
1@Service 2public class IncomeOutgoService { 3 @Autowired 4 private IncomeOutgoRepository incomeOutgoRepository; 5 6 public List<IncomeOutgo> findByMonth(String month){ 7 return incomeOutgoRepository.findByMonth(month); 8 } 9}
Controller
java
1@Controller 2@RequestMapping("/") 3public class IncomeOutgoController { 4 @Autowired 5 private IncomeOutgoService incomeOutgoService; 6 7 @GetMapping("month") 8 public String month(Model model){ 9 10 //今日の日付 11 Date today = new Date(); 12 13 // 年月の文字列(例:2018-12) 14 SimpleDateFormat thisMonthPathFormat = new SimpleDateFormat("yyyy-MM"); 15 String thisMonthPath = thisMonthPathFormat.format(today); 16 17 // 月別一覧表示 18 List<IncomeOutgo> monthList = incomeOutgoService.findByMonth(thisMonthPath); 19 model.addAttribute("monthList", monthList); 20 return "/month"; 21 } 22}
テーブルの中身はこちら
+----+-------------+------+------------+-----------+-------+ | id | category_id | cost | date | memo | type | +----+-------------+------+------------+-----------+-------+ | 1 | 1 | 1000 | 2018-12-07 | ランチ | outgo | | 2 | 1 | 500 | 2018-11-05 | お菓子 | outgo | +----+-------------+------+------------+-----------+-------+
回答1件
あなたの回答
tips
プレビュー