Spring Boot Data Access with MyBatis Integration
MyBatis serves as a lightweight persistence framework that decouples SQL logic from Java application code. Unlike full-featured ORM solutions, it provides granular control over database operations while eliminating boilerplate JDBC code. The framework supports dynamic SQL construction, automatic result mapping to POJOs, and declarative transaction management through Spring integration.
To incorporate MyBatis into a Spring Boot project, begin by adding the starter dependency along with your database driver. For Maven-based projects:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
Configure the connection pool in application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/inventory_db
spring.datasource.username=app_user
spring.datasource.password=secure_pass
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Define a domain entity representing your table structure:
public class Product {
private Long productId;
private String productName;
private BigDecimal unitPrice;
private Integer stockQuantity;
// Getters and setters omitted for brevity
}
Create a Mapper interface to handle data base operations. Annotate the interface with @Mapper and define queries using annotasions:
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface ProductMapper {
@Select("SELECT product_id, product_name, unit_price, stock_quantity FROM products WHERE product_id = #{id}")
Product selectByPrimaryKey(@Param("id") Long id);
@Select("SELECT * FROM products WHERE stock_quantity > #{threshold}")
List<Product> findAvailableInventory(@Param("threshold") Integer minStock);
}
Implement the service layer to encapsulate business logic:
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class InventoryService {
private final ProductMapper productMapper;
public InventoryService(ProductMapper productMapper) {
this.productMapper = productMapper;
}
public Product getProductDetails(Long identifier) {
return productMapper.selectByPrimaryKey(identifier);
}
public List<Product> fetchLowStockItems(Integer threshold) {
return productMapper.findAvailableInventory(threshold);
}
}
Expose the functionality through a REST controller:
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/inventory")
public class InventoryController {
private final InventoryService inventoryService;
public InventoryController(InventoryService inventoryService) {
this.inventoryService = inventoryService;
}
@GetMapping("/products/{productId}")
public Product getProduct(@PathVariable Long productId) {
return inventoryService.getProductDetails(productId);
}
@GetMapping("/products/available")
public List<Product> getAvailableProducts(@RequestParam(defaultValue = "10") Integer minStock) {
return inventoryService.fetchLowStockItems(minStock);
}
}
Enable component scanning for MyBatis mappers by adding @MapperScan to your main application class:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.inventory.mapper")
public class InventoryApplication {
public static void main(String[] args) {
SpringApplication.run(InventoryApplication.class, args);
}
}
This configuration establishes a complete data access layer where MyBatis handles SQL execution and result mapping while Spring Boot manages dependency injection and transaction boundaries.