SpringBootとMyBatisの統合方法はどのようにすればいいですか?
Spring BootとMyBatisを統合するには、以下の手順に従って操作することができます。
手順1:pom.xmlファイルにMyBatisとMyBatis-Spring-Boot-Starterの依存関係を追加してください。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
ステップ2:データベース接続情報とMyBatisプロパティを設定します。
application.propertiesまたはapplication.ymlファイルに以下の設定を追加してください。
spring.datasource.url=jdbc:mysql://localhost:3306/db_example
spring.datasource.username=db_username
spring.datasource.password=db_password
mybatis.mapper-locations=classpath*:mapper/*.xml
ステップ3:MyBatisのMapperインターフェースと対応するXMLファイルを作成してください。
UserMapper.javaというMapperインターフェースを作成し、Mapperメソッドを記述してください。
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("select * from users")
List<User> getAllUsers();
}
resources/mapperディレクトリにUserMapper.xmlファイルを作成し、SQL文を設定してください。
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.entity.User">
<id column="id" property="id" />
<result column="name" property="name" />
<result column="email" property="email" />
</resultMap>
<select id="getAllUsers" resultMap="BaseResultMap">
select * from users
</select>
</mapper>
ステップ4:サービスとコントローラーを作成する。
UserServiceインターフェースとUserServiceImpl実装クラスを作成します。
public interface UserService {
List<User> getAllUsers();
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
}
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
}
Spring BootとMyBatisを統合する基本的な手順は以上です。Spring Bootを起動すると、MyBatisは自動的に設定ファイルとアノテーションをスキャンしてMapperインターフェースを生成し、そのプロクシ実装クラスを生成します。これらのMapperインターフェースを使用してデータベースにアクセスできます。