Last year, I had a little understanding of how convenient and fast SpringBoot was developed in various channels. But I didn't study hard at that time. After all, I felt that I was not very proficient in Struts and SpringMVC. However, after reading a lot of introductions about SpringBoot, it was not as difficult as I thought, so I began to prepare to learn SpringBoot. In my spare time, after reading SpringBoot actual combat and some masters’ blogs about SpringBoot, I started writing my first SpringBoot project. After being able to implement CRUD functions in SpringBoot with some simple development of Restful-style interfaces, this blog post was created.
Introduction to SpringBoot
Spring Boot is a new framework provided by the Pivotal team. It is designed to simplify the initial construction and development process of new Spring applications. The framework uses a specific way to configure it, so that developers no longer need to define boilerplate configurations.
Simply put, you can quickly develop a project with just a few jars and some simple configurations.
If I want to simply develop an external interface, then I only need the following code.
A main program starts springBoot
@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Control layer
@RestControllerpublic class HelloWorldController { @RequestMapping("/hello") public String index() { return "Hello World"; } }After successfully starting the main program, write the control layer, and then enter http://localhost:8080//hello in the browser to view the information.
I feel that using SpringBoot to develop programs is very simple!
In SpringBoot's practical words:
There is no configuration here, no web.xml, no build instructions, and even no application server, but that's the whole application. SpringBoot will do all the logistics required to execute the application, and you just need to get the application's code.
Develop a Restful service based on SpringBoot
Before developing a program, you should make some preparations
CREATE DATABASE `springboot`;USE `springboot`;DROP TABLE IF EXISTS `t_user`;CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', `name` varchar(10) DEFAULT NULL COMMENT 'name', `age` int(2) DEFAULT NULL COMMENT 'Age', PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
The most core jar of springBoot
spring-boot-starter: core module, including automatic configuration support, logging and YAML;
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> <mybatis-spring-boot>1.2.0</mybatis-spring-boot> <mysql-connector>5.1.39</mysql-connector> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- Spring Boot Mybatis Dependency --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring-boot}</version> </dependency> <!-- MySQL connection driver dependency--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector}</version> </dependency> </dependency> <build> <plugins> <!--Use SpringBoot plug-in to use the spring-boot-devtools module application. When the file in the classpath changes, it will automatically restart! --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork> </configuration> </plugin> </plugins> </build> com.pancm.web - Controller layer
com.pancm.dao - Data Operation Layer DAO
com.pancm.bean - Entity Class
com.pancm.bean.service - Business logic layer
Application - Application Startup Class
application.properties - Application configuration file, the configuration will be automatically read by the application startup
Generally, we need some custom configurations, such as configuring the connection configuration of jdbc, where we can use application.properties to configure it. The actual configuration of the data source shall be subject to everyone's.
## Data source configuration spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver## Mybatis configuration# Configure as com.pancm.bean Point to the entity class package path. mybatis.typeAliasesPackage=com.pancm.bean# Configure the mapper package under the classpath path, * means that all xml files will be scanned. mybatis.mapperLocations=classpath/:mapper/*.xml
It's almost time to come to the key code.
We start by writing the pojo class, corresponding to the t_user table in the database.
The code is as follows
public class User { /** Number*/ private int id; /** Name*/ private String name; /** Age*/ private int age; public User(){ } public class User { /** Number*/ private int id; /** Name*/ private String name; /** Age*/ private int age; public User(){ }// getter and setter omitted}In the previous Dao layer, both hibernate and mybatis could use annotations or mapper configuration files. Here we use spring's JPA to complete CRUD.
illustrate:
There are generally two ways to implement CRUD and database implementation:
The first is the mapper configuration of xml.
The second type is to use annotations, @Insert, @Select, @Update, @Delete and other annotations. This article uses the second type
import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Mapper;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import org.springframework.data.repository.query.Param;import com.pancm.bean.User;@Mapperpublic interface UserDao { /** * User data added*/ @Insert("insert into t_user(id,name,age) values (#{id},#{name},#{age})") void addUser(User user); /** * User data modification*/ @Update("update t_user set name=#{name},age=#{age} where id=#{id}") void updateUser(User user); /** * User data deletion*/ @Delete("delete from t_user where id=#{id}") void deleteUser(int id); /** * Query user information based on user name* */ @Select("SELECT id,name,age FROM t_user") // Return Map result set @Results({ @Result(property = "id", column = "id"), @Result(property = "name", column = "name"), @Result(property = "age", column = "age"), }) User findByName(@Param("name") String userName); /** * Query user information based on user ID* */ @Select("SELECT id,name,age FROM t_user") User findById(@Param("id") int userId); /** * Query user information based on user age*/ @Select("SELECT id,name,age FROM t_user where age = #{userAge}") User findByAge( int userAge);}Personal understanding of the annotations used by this interface:
mapper: Added this annotation to the interface to indicate that this interface is a CRUD implemented based on annotation.
Results: The returned map result set, property represents the fields of the User class, and column represents the fields of the corresponding database.
Param: field for sql condition.
Insert, Select, Update, Delete: Recruit, modify, and delete corresponding databases.
This is basically the same as hibernate and mybatis.
The code is as follows:
interface
import com.pancm.bean.User;/** * * Title: UserService* Description:User Interface* Version:1.0.0 * @author pancm* @date January 9, 2018*/public interface UserService { /** * Add user* @param user * @return */ boolean addUser(User user); /** * Modify user* @param user * @return */ boolean updateUser(User user); /** * Delete user* @param id * @return */ boolean deleteUser(int id); /** * Query user information based on user name* @param userName */ User findUserByName(String userName); /** * Query user information based on user ID* @param userId */ User findUserById(int userId); /** * Query user information based on user ID* @param userAge */ User findUserByAge(int userAge);}Implementation Class
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.pancm.bean.User;import com.pancm.dao.UserDao;import com.pancm.service.UserService;/** * * Title: UserServiceImpl* Description:* User Operation Implementation Class* Version:1.0.0 * @author pancm* @date January 9, 2018*/@Servicepublic class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Override public boolean addUser(User user) { boolean flag=false; try{ userDao.addUser(user); flag=true; } catch(Exception e){ e.printStackTrace(); } return flag; } @Override public boolean updateUser(User user) { boolean flag=false; try{ userDao.updateUser(user); flag=true; } catch(Exception e){ e.printStackTrace(); } return flag; } @Override public boolean deleteUser(int id) { boolean flag=false; try{ userDao.deleteUser(id); flag=true; }catch(Exception e){ e.printStackTrace(); } return flag; } @Override public User findUserByName(String userName) { return userDao.findByName(userName); } @Override public User findUserById(int userId) { return userDao.findById(userId); } @Override public User findUserByAge(int userAge) { return userDao.findByAge(userAge); }}The control layer is very similar to springMVC, but it is much simpler than that.
My personal understanding of the annotation about the control layer is as follows:
RestController: The methods in the default class will be returned in json format.
RequestMapping: Interface path configuration.
method : Request format.
RequestParam: Request parameters.
The specific implementation is as follows:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import com.pancm.bean.User;import com.pancm.service.UserService;/** * * Title: UserRestController* Description: * User Data Operation Interface* Version:1.0.0 * @author pancm* @date January 9, 2018*/@RestController@RequestMapping(value = "/api/user")public class UserRestController { @Autowired private UserService userService; @RequestMapping(value = "/addUser", method = RequestMethod.POST) public boolean addUser( User user) { System.out.println("Start to add..."); return userService.addUser(user); } @RequestMapping(value = "/updateUser", method = RequestMethod.PUT) public boolean updateUser(User user) { System.out.println("Start to update..."); return userService.updateUser(user); } @RequestMapping(value = "/deleteUser", method = RequestMethod.DELETE) public boolean delete(@RequestParam(value = "userName", required = true) int userId) { System.out.println("Start delete..."); return userService.deleteUser(userId); } @RequestMapping(value = "/userName", method = RequestMethod.GET) public User findByUserName(@RequestParam(value = "userName", required = true) String userName) { System.out.println("Start query..."); return userService.findUserByName(userName); } @RequestMapping(value = "/userId", method = RequestMethod.GET) public User findByUserId(@RequestParam(value = "userId", required = true) int userId) { System.out.println("Start query..."); return userService.findUserById(userId); } @RequestMapping(value = "/userAge", method = RequestMethod.GET) public User findByUserAge(@RequestParam(value = "userAge", required = true) int userAge) { System.out.println("Start query..."); return userService.findUserById(userAge); }}SpringApplication is a class used to start Spring applications from the main method.
By default, it performs the following steps:
1. Create a suitable ApplicationContext instance (depending on classpath).
2. Register a CommandLinePropertySource to use command line parameters as Spring properties.
3. Refresh the application context and load all singleton beans.
4. Activate all CommandLineRunner beans.
Start this class directly using main, and SpringBoot will automatically configure it.
ps: Even now I still think this is really amazing.
Some annotations for this class are explained. :
SpringBootApplication: Turn on component scanning and automatic configuration.
MapperScan: mapper interface class scan package configuration
The code is as follows:
import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;/** * * Title: Application* Description:* springBoot Main Program* Version:1.0.0 * @author pancm* @date January 5, 2018*/@SpringBootApplication@MapperScan("com.pancm.dao")public class Application { public static void main(String[] args) { // Start the embedded Tomcat and initialize the Spring environment and its Spring components SpringApplication.run(Application.class, args); System.out.println("Program is running..."); }}After the code is written, we conduct the code test.
After starting Application, use the postman tool to test the interface.
The test results are as follows:
Only one get and post test is used here. The actual methods have been tested, but I feel that there is no need to stick the map.
I put the project on github:
https://github.com/xuwujing/springBoot
Summarize
The above is the editor’s introduction to develop a Restful service based on SpringBoot to implement the function of adding, deleting, modifying and checking. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!