Spring Boot Tutorial: Building a Rental Service with MyBatis Integration
This article provides a step‑by‑step guide to creating a Spring Boot application, generating a project template, adding a MyBatis‑based persistence layer, implementing service and controller layers, configuring the database, and running the application to expose REST endpoints.
Spring Boot Concept
Spring Boot is a collection of libraries that simplifies the creation of stand‑alone Spring applications, provides an embedded Tomcat server, reduces Maven configuration, offers auto‑configuration, and includes production‑ready features such as metrics and health checks.
Setting Up Spring Boot
1. Generate a project template at https://start.spring.io/ and import it into IntelliJ IDEA.
2. Create a controller (see image).
3. Run the project by adding @ComponentScan and executing the application. After the compilation succeeds, open a browser and visit http://localhost:8080/index to see the result.
Integrating MyBatis
MyBatis is a powerful persistence framework that supports custom SQL, stored procedures, and advanced mappings.
In pom.xml add the following dependencies:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>Create the database and users table:
use zuche;
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`age` int(10) NOT NULL,
`phone` bigint NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO users VALUES (1,'赵',23,158,'[email protected]');
INSERT INTO users VALUES (2,'钱',27,136,'[email protected]');
INSERT INTO users VALUES (3,'孙',31,159,'[email protected]');
INSERT INTO users VALUES (4,'李',35,130,'[email protected]');Domain Model
Create the User POJO:
package com.athm.pojo;
public class User {
private int id;
private String username;
private Integer age;
private Integer phone;
private String email;
// getters and setters omitted for brevity
}Mapper Interface
Define UserMapper with a MyBatis @Select statement:
package com.athm.dao;
import com.athm.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT id,username,age,phone,email FROM USERS WHERE AGE=#{age}")
List<User> getUser(int age);
}Service Layer
Define the service interface and its implementation:
package com.athm.service;
import com.athm.pojo.User;
import java.util.List;
public interface UserService {
List<User> getUser(int age);
} package com.athm.service;
import com.athm.dao.UserMapper;
import com.athm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> getUser(int age) {
return userMapper.getUser(age);
}
}Controller
Expose two endpoints: a REST API returning users by age and a simple map endpoint.
package com.athm.controller;
import com.athm.pojo.User;
import com.athm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class IndexController {
@Autowired
UserService userService;
@GetMapping("/show")
public List<User> getUser(int age) {
return userService.getUser(age);
}
@RequestMapping("/index")
public Map<String, String> index() {
Map<String, String> map = new HashMap<>();
map.put("北京", "北方城市");
map.put("深圳", "南方城市");
return map;
}
}Application Class
Configure component scanning and MyBatis mapper scanning:
package com.athm.zuche;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.athm.controller", "com.athm.service"})
@MapperScan(basePackages = {"com.athm.dao"})
public class ZucheApplication {
public static void main(String[] args) {
SpringApplication.run(ZucheApplication.class, args);
}
}Configuration
Add the following properties to application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/zuche
spring.datasource.username=toutou
spring.datasource.password=*******
spring.datasource.driver-class-name=com.mysql.jdbc.DriverRunning the Application
Start the Spring Boot application, then open a browser and navigate to http://localhost:8080/show?age=30 to retrieve users older than 30, or visit http://localhost:8080/index to see the map response.
GitHub Repository
The complete source code is available at https://github.com/toutouge/javademo/tree/master/zuche_test/zuche .
Conclusion
System failures are often unpredictable; therefore, designers must anticipate risks and implement safeguards to ensure reliability.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
