In this chapter, we set up the basic framework structure of the project and integrate Mybatis. Project required environment JDk1.8, Maven, mysql database; Development tool IDEA. If you have any questions, please contact me at [email protected]. Ask for directions of various gods, thank you

I. Build the basic framework through idea tool



2. Click Next and configure as shown below



3. Click Next and configure as shown below. Here we select database
MySQLAnd persistence layer framework
MyBatis



4. Click Next, select the working directory, and click Finish to start the build


5. After the creation, the project directory structure is as follows

Demoappliction.java is the project’s startup class

Application.properties is the project configuration file

Pom. XML describes the project’s Maven coordinates, dependencies, rules developers need to follow, defect management systems, organizations and licenses, and all other project-related factors. It is a project-level configuration file (in English: managing jar packages required by the project).


2. Configure the database information

Add the following database configuration to the application.properties file

spring.datasource.url=jdbc:mysql://localhost:3306/demo? useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=falseSpring spring. The datasource. The username = database user name. The datasource. The password = password database spring.datasource.driverClassName=com.mysql.jdbc.DriverCopy the code

Create table UserInfo

CREATE TABLE `user_info` (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; Copy the code

Create the basic directory structure of the project



Model

package com.example.demo.model; import javax.persistence.Column; import javax.persistence.Id; /** * @author * @description: * @time 2018/4/18 11:55 */ public class UserInfo {/** * private String id; /** * userName */ private String userName; private String password; public StringgetId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) { this.password = password; }}Copy the code

Mapper

<? xml version="1.0" encoding="UTF-8"? > <! DOCTYPE mapper PUBLIC"- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.dao.UserInfoMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.model.UserInfo">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="user_name" jdbcType="VARCHAR" property="userName"/>
    </resultMap>

    <sql id="Base_Column_List">
      id,user_name
    </sql>

    <select id="selectById" parameterType="java.lang.Integer" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from user_info
        where id = #{id,jdbcType=VARCHAR}
    </select>

</mapper>
Copy the code

Dao

package com.example.demo.dao; import com.example.demo.model.UserInfo; import org.apache.ibatis.annotations.Param; /** * @author * @description: * @time 2018/4/18 11:54 */ public interface UserInfoMapper { UserInfo selectById(@Param("id") Integer id);
}Copy the code

Service

package com.example.demo.service; import com.example.demo.model.UserInfo; /** * @author * @description: * @time 2018/4/18 11:56 */ public interface UserInfoService { UserInfo selectById(Integer id); }Copy the code

ServiceImpl

package com.example.demo.service.impl; import com.example.demo.dao.UserInfoMapper; import com.example.demo.model.UserInfo; import com.example.demo.service.UserInfoService; import org.springframework.stereotype.Service; import javax.annotation.Resource; /** * @author * @description: * @time 2018/4/18 11:56 */ @Service public class UserInfoServiceImpl implements UserInfoService{ @Resource private UserInfoMapper userInfoMapper; public UserInfo selectById(Integer id){returnuserInfoMapper.selectById(id); }}Copy the code

Controller

package com.example.demo.controller; import com.example.demo.model.UserInfo; import com.example.demo.service.UserInfoService; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; /** * @author * @description: * @time 2018/4/18 11:39 */ @restController @requestMapping ("userInfo")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/hello")
    public String hello() {return "hello SpringBoot";
    }

    @PostMapping("/selectById")
    public UserInfo selectById(Integer id){
        returnuserInfoService.selectById(id); }}Copy the code

The @restController annotation is used for:

@restController is composed of @Controller and @responseBody, indicating that the class is Controller and returns JSON data, not the page path.


Focus on MyBatisConfigurer. Java in Configurer

package com.example.demo.core.configurer; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import javax.sql.DataSource; /** * @ClassName: MybatisConfigurer * @Description: @date 2018 月20日 4:03:46 * */ @configuration Public class MybatisConfigurer {@bean public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setTypeAliasesPackage("com.example.demo.model"); / / add the XML directory ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver (); factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
      return factory.getObject();
   }

   @Bean
   public MapperScannerConfigurer mapperScannerConfigurer() {
      MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
      mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
      mapperScannerConfigurer.setBasePackage("com.example.demo.dao");
      returnmapperScannerConfigurer; }}Copy the code

@configuration indicates that the file is a Configuration file

@bean indicates that the method is <Bean ID =””></Bean> in a traditional XML configuration file

Which factory. SetTypeAliasesPackage (” com. Example. The demo. The model “) for the model of a project storage paths;

factory.setMapperLocations(resolver.getResources(“classpath:mapper/*.xml”)); Mapper. XML storage path;

mapperScannerConfigurer.setBasePackage(“com.example.demo.dao”); Represents the storage path of the DAO layer

Five: running the project

Go to DemoApplication, right-click, and select Run DemoApplication

If the following information is displayed on the console, the startup is successful



Six: test interface

Open Postman (a Google browser plugin that can be downloaded from the App Store) and type in



Change your OWN IP address. If the following structure data occurs, the access succeeds

{
    "id": 1,
    "userName": "1"
}Copy the code

The project address

Code cloud address: gitee.com/beany/mySpr…

GitHub address: github.com/MyBeany/myS…

Writing articles is not easy, if it is helpful to you, please help click star

At the end

Framework building and mybatis integration have been completed, and the subsequent functions will be updated successively. If you have any questions, please contact me at [email protected]. Ask for directions from various gods, thank you.