• This article was originally written by AriesHoo.
  • 【 making – AriesHoo 】
  • [Nuggets -AriesHoo]

IDEA+Spring boot+Mybatis+Mysql front-end interface development

IDEA+Spring Boot +Mybatis+Mysql front-end interface development (2) targeted

Following the previous chapter – preparation of the development environment and tools, this article formally opened the code

The target

First determine interface development goal, in this the most projects will use to the user login, registration, for example, do a support account registration + binding three-way (qq, WeChat) login + binding mobile phone number and support swagger preview debug interface program, the article tells only one see the full interface implementation process other interface API – demo project.

Create databases and tables

1. The user table generally includes field ID, account number, password, mobile phone number, wechat ID, QQID, etc. Create user table as follows:

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` varchar(64) NOT NULL COMMENT 'user ID',
  `user_name` varchar(64) NOT NULL COMMENT 'Username - Account can be used for login',
  `nick_name` varchar(64) DEFAULT ' ' COMMENT 'User name',
  `password` varchar(128) NOT NULL COMMENT 'password',
  `phone` varchar(11) DEFAULT ' ' COMMENT 'Phone number',
  `we_chat_open_id` varchar(64) DEFAULT ' ' COMMENT 'wechat Authorization ID',
  `qq_open_id` varchar(64) DEFAULT ' ' COMMENT 'qq authorization id',
  `head_url` varchar(256) DEFAULT ' ' COMMENT 'Avatar address',
  `signature` varchar(128) DEFAULT ' ' COMMENT 'Personal Signature',
  `create_time` datetime DEFAULT 'the 2018-01-01 00:00:01' COMMENT 'Creation time',
  `login_time` datetime DEFAULT 'the 2018-01-01 00:00:01' COMMENT 'Last login time',
  `modify_time` datetime DEFAULT 'the 2018-01-01 00:00:01' COMMENT 'Modification time',
  PRIMARY KEY (`id`,`user_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy the code

Create database ah_test — see section 2 – Development environment and tools -Navicat connect to MySQL.

3, create user table method 1: click Navicat navigation bar query and select New query to create the above code copy to run

Method 2: You can also manually create a database table by right-clicking ah_test and selecting New table

You are advised to use Method 1 to create a user table.

New project

1, open IDEA and select File–>>New –>>Projects, as shown in the flowchart

Finally, select the project save location Finish to create the project.

The directory structure of the successfully created project is as follows:

XML for the tripartite library. 3. Application. Properties for the project configuration file, such as port configuration, database connection configuration

It is recommended to create a new application.yml instead of application.properties as the project configuration. The author also uses online means here.

Project to write

1. Configure port and database connection information

server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/ah_test? useUnicode=true&amp&characterEncoding=utf-8 # Pay attention to the encoding format
    username: root
    password:
Copy the code

In the command, localhost:3306 is the host address, and the port number is also set through Navicat to connect to the database. Ah_test indicates the database name created earlier. Username and password indicate the username and password for logging in to the database.

2. First run the project

After the configuration is complete, run the project and you will probably see the following error:

This problem is caused by the MySQL time zone setting

The solution is to add the following Settings to the database URL: **&amp&serverTimezone=UTC**

Complete configuration:

server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/ah_test? useUnicode=true&amp&characterEncoding=utf-8&amp&serverTimezone=UTC # Pay attention to setting the encoding format timely area
    username: root
    password:
Copy the code

3. Create subcontracts and create related classes

As shown in the figure:

1. Controller is the method corresponding to the interface finally provided to the front end; entity is the entity class (bean class); Mapper is the mapping relationship class configured to query the database (described later); Service is the bridge between Controller and Mapper

Create mapper.xml

Create usermapper. XML under Mybatis and point to the usermapper. Java class under Java package.

The XML writes the SQL statement, and the Java directory controller–>> Service –>> Mapper finally executes the SQL code in the XML

5. Configure MyBatis

5.1 Add the following configuration in the project configuration file application.yml

The configuration node is an independent node
mybatis:
  mapper-locations: classpath:mybatis/*.xml  Note: It must correspond to the path of the mapper mapping XML file
  type-aliases-package: com.aries.api.demo.entity  Note: the path of the corresponding entity class
  configuration:
    map-underscore-to-camel-case: true # Database field underline automatically hump
Copy the code

Mapper-locations Specifies the XML path

5.2. Next, add the Mapper path under the Java directory through @mapperscan in the entry Application class, as shown in the figure:

The sample Demo uses the entry class add mode.

5.3 Controller configuration annotation @restController indicates that this class is an interface class. You can also add @requestMapping to add the same start to the interface methods of the same controller for module identification, as shown in the figure

6. Main code writing

Take searching user information by account number/mobile phone number/wechat account/ID as an example. Others can be viewed in the complete project API-Demo

Java directory UserMapper code

/** * Query user ** @param account * @ by account/mobile phone numberreturn
     */
    UserEntity findUserById(String account);
Copy the code

UserService code

  @Autowired
  private UserMapper mMapper;

  public UserEntity findUserById(String account) {
        return mMapper.findUserById(account);
    }
Copy the code

UserController code

    @Autowired
    private UserService mUserService;
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public BaseEntity getUserInfo(@RequestParam(value = "id") @ApiParam("User ID - Login registration returns the ID field in the user entity") String id) {
        UserEntity userEntity = mUserService.findUserById(id);
        if (StringUtils.isEmpty(id)) {
            return new BaseEntity()
                    .setMsg("Please enter user ID")
                    .setCode(201);
        }
        if(userEntity ! = null) {return BaseEntity.
                    success("Obtaining user information successfully")
                    .setData(userEntity);
        }
        return new BaseEntity()
                .setMsg("There is no information about this account at present")
                .setCode(201);
    }

Copy the code

1, RequestMapping value indicates that the interface method name As RequestMapping final Controller Settings interface address is: HTTP: localhost: 8080 / user/getUserInfo method Specifies the interface access mode as get. Others include requestMethod. POST, etc. RequestParam specifies a single parameter, or @RequestBody can pass a JSON string, depending on your preference and how many parameters and extensibility

Mapper queries database Settings in XML

   <select id="findUserById" resultType="com.aries.api.demo.entity.UserEntity">
        select 
        	*
        	,UNIX_TIMESTAMP(create_time) as create_date
        from 
        	t_user
        where
        	id = #{account} or user_name = #{account} or phone = #{account}or we_chat_open_id = #{account}or qq_open_id = #{account};
    </select>
Copy the code

1. There is a mapping relationship between mapper in XML and Mapper in Java, so the ID in XML and the method name in Java must correspond one by one; otherwise, the corresponding method cannot be found. Entity 3, #{XXX} marked as Java mapper method transfer parameter, must correspond to the front of the database corresponding field name 4, can be executed in Navicat query statement after the dynamic parameter adjustment

7. Run application and browser tests

8. Integrate Swagger

1. Import the plug-in –pom.xml version of your choice

<! --Swagger UI--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> < version > 2.8.0 < / version > < / dependency > < the dependency > < groupId >. IO springfox < / groupId > < artifactId > springfox swagger - UI < / artifactId > < version > 2.8.0 < / version > < / dependency > < the dependency > < the groupId > IO. Springfox < / groupId > < artifactId > springfox - bean - the validators < / artifactId > < version > 2.8.0 < / version > </dependency>Copy the code

2. Add Swagger configuration class

Create the SwaggerConfig class in the Java package and add the @Configuration@enablesWagger2 annotation

The main createRestApi apis specify the Controller path

3. Controller configuration

Add @api (value = “/user”, description = “user module “, Tags = {“/user”}) annotation description file tags for the description text before the tag value is not found yet UI withdrawal interface method parameter add annotation @apiparam (” user ID – login registration returns the id field in the user entity “) annotation field

4. Run the project and show the effect

Program compiled after the operation, the browser simply enter http://localhost:8080/swagger-ui.html access to check the effect

Click the module to input interface parameters to access the debugging interface

conclusion

So far a simple user login, registration related background interface project written, of course, the actual project business logic is certainly more complex than this, but with this demo writing experience other side to do while learning can learn more.

About me

The Denver nuggets: AriesHoo

GitHub: AriesHoo

Email: [email protected]