前提
SpringBootからMyBatisを用いてMySQLに接続するミニマムコードを作成したいです。
起動時エラーでマッパーがBeanとして認識されていない?ようなエラーで詰まっています。
なにが不足している、または間違っているかわかりますでしょうか?
発生している問題・エラーメッセージ
SampleService required a bean of type 'jp.co.demo.mapper.SampleMapper' that could not be found.
該当のソースコード
pom.xml
xml
1<dependency> 2 <groupId>mysql</groupId> 3 <artifactId>mysql-connector-java</artifactId> 4</dependency> 5<dependency> 6 <groupId>org.mybatis.spring.boot</groupId> 7 <artifactId>mybatis-spring-boot-starter</artifactId> 8 <version>2.1.3</version> 9</dependency>
application.properties
properties
1spring.datasource.url = jdbc:mysql://localhost:3306/test-db 2spring.datasource.username = root 3spring.datasource.password = pass 4spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
java
1package jp.co.demo.bean; 2 3public class SampleUserBean { 4 private int user_id; 5 private String user_name; 6 private String password; 7 8 public int getUser_id() { 9 return user_id; 10 } 11 12 public void setUser_id(int user_id) { 13 this.user_id = user_id; 14 } 15 16 public String getUser_name() { 17 return user_name; 18 } 19 20 public void setUser_name(String user_name) { 21 this.user_name = user_name; 22 } 23 24 public String getPassword() { 25 return password; 26 } 27 28 public void setPassword(String password) { 29 this.password = password; 30 } 31}
java
1package jp.co.demo.controller; 2 3import org.springframework.beans.factory.annotation.Autowired; 4import org.springframework.stereotype.Controller; 5import org.springframework.web.bind.annotation.GetMapping; 6 7import jp.co.demo.service.SampleService; 8 9@Controller 10public class SampleController { 11 @Autowired 12 private SampleService sampleService; 13 14 @GetMapping("/sample") 15 public String sample() { 16 sampleService.sample(); 17 return "sample"; 18 } 19} 20
java
1package jp.co.demo.mapper; 2 3import java.util.List; 4 5import org.apache.ibatis.annotations.Mapper; 6import org.apache.ibatis.annotations.Select; 7 8import jp.co.demo.bean.SampleUserBean; 9 10@Mapper 11public interface SampleMapper { 12 @Select("select * from m_users;") 13 List<SampleUserBean> selectAll(); 14}
java
1package jp.co.demo.service; 2 3import java.util.List; 4 5import org.springframework.beans.factory.annotation.Autowired; 6import org.springframework.stereotype.Service; 7 8import jp.co.demo.bean.SampleUserBean; 9import jp.co.demo.mapper.SampleMapper; 10 11@Service 12public class SampleService { 13 @Autowired 14 private SampleMapper sampleMapper; 15 16 public void sample() { 17 List<SampleUserBean> users = sampleMapper.selectAll(); 18 19 for (SampleUserBean user : users) { 20 System.out.println(user.getUser_id() + ", " + user.getUser_name() + " " + user.getPassword()); 21 } 22 } 23}
試したこと
SampleApplication.javaに@MapperScanを指定してみましたが同じエラーでした。
@Mapperアノテーションが付与されてクラスを自動で認識するので@MapperScanは不要という記事を見たので、これが原因ではないと考えています。
あなたの回答
tips
プレビュー