The spring boot series integrates MyBatis framework

Posted by Jragon on Sat, 13 Jun 2020 20:59:15 +0200

Add Dependency

<!--Add to mysql and mybatis rely on-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

Configure MyBatis

@Configuration
@MapperScan("com.example.springbootstartlearn.Dao")
public class MyBatisConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // Scan moudel
        factoryBean.setTypeAliasesPackage("com.example.springbootstartlearn.Moudel");
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml"));

        return  factoryBean.getObject();
    }
}

Configure Data Source

Instead of using the properties configuration file, use the yml configuration file, which is configured as follows

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.1.8:3306/studenms?useUnicode=true&zeroDateTimeBehavior=CONVERT_TO_NULL&autoReconnect=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: sa

Write a dao

The model definition is no longer written here, it's a java class, defined by the field of the database, but implemented the getter/setter method and construction method

@Repository("userDao")
public interface UserDao {

    public List<UserMoudel> findAll();

    public UserMoudel findById(int id);


    public boolean update(UserMoudel moudel);
}

To configureSqlmapper.xml

<mapper namespace="com.example.springbootstartlearn.Dao.UserDao">
    <!-- sql mapping -->

    <select id="findAll" resultType="com.example.springbootstartlearn.Moudel.UserMoudel" >
        select * from t_user
    </select>

    <select id="findById" resultType="com.example.springbootstartlearn.Moudel.UserMoudel">
        select * from t_user where id=#{id}
    </select>

    <update id="update" parameterType="com.example.springbootstartlearn.Dao.UserDao">
        update t_user
        <trim prefix="set" suffixOverrides=",">
            <if test="user != null">user=#{user},</if>
            <if test="role != null">role=#{role},</if>
            <if test="name != null">name=#{name},</if>
            <if test="email != null">email=#{email},</if>
            <if test="password != null">password=#{password}</if>
        </trim>
        where id=#{id}
    </update>
</mapper>

Write service and serviceImpl

service

public interface IUserSvc {

    public List<UserMoudel> findAll();

    public UserMoudel findById(int id);


    public boolean update(UserMoudel moudel);
}

serviceImpl

@Service("userSvc")
public class UserSvcImpl implements IUserSvc {

    @Autowired
    private UserDao dao;

    @Override
    public List<UserMoudel> findAll() {
      return dao.findAll();
    }

    @Override
    public UserMoudel findById(int id) {
       return  dao.findById(id);
    }

    @Override
    public boolean update(UserMoudel moudel) {
        return  dao.update(moudel);
    }
}

Write Controller and integrate swagger

@Api("User Information Service Interface")
@RestController
@RequestMapping(value = "user")
public class UserController {

    @Autowired
    private UserSvcImpl userSvc;

    @ApiOperation("Get all user information")
    @GetMapping(value = "/findAll")
    @ResponseBody
    public List<UserMoudel> findAll() {
        return userSvc.findAll();
    }

    @ApiOperation(value = "According to user Id Query user information")
    @GetMapping(value = "/findById")
    @ResponseBody
    public UserMoudel findById(@RequestParam(value = "user Id",required = true) int id){
        return userSvc.findById(id);
    }

    @ApiOperation("Update user information")
    @PutMapping("/update")
    @ResponseBody
    public boolean update(@RequestBody UserMoudel moudel){
        return userSvc.update(moudel);
    }
}

The swagger interface list is as follows

The test results for each interface are as follows:

findAll interface

findById interface:

update interface

Before updating the database:

After executing the interface

Problems encountered

  1. Initialization of the data source failed with the following exception information:

Usually this is due to incorrect data source connection information or inconsistent driver and database versions

swagger and spring boot attribute annotations

@Api: Used on a class to illustrate its role
 @ApiOperation: Used in a method to illustrate the effect of the method
 @ApiImplicitParams: Used to include a set of parameter descriptions on a method
 @ApiImplicitParam: Used in the @ApiImplicitParams comment to specify aspects of a request parameter
    paramType: Where to place the parameter
        Header-->Get request parameters: @RequestHeader
        Query-->Get request parameters: @RequestParam
        path (for restful interface)-->Get request parameters: @PathVariable
        body (not commonly used)
        form (not commonly used)
    Name: parameter name
    dataType: Parameter type
    required: whether the parameter must be passed
    value: what the parameter means
    defaultValue: The default value of the parameter
 @ApiResponses: Used to represent a set of responses
 @ApiResponse: Used in @ApiResponses to convey an incorrect response message
    code: a number, such as 400
    message: information, such as "request parameter error"
    response: class that throws an exception
 @ApiModel: Describes information about a Model (this is typically used when post s are created using a scenario such as @RequestBody where request parameters cannot be described using the @ApiImplicitParam annotation)
    @ApiModelProperty: Describes the properties of a model

Topics: Programming MySQL Mybatis Spring Database