Spring Boot統合MyBatis汎用Mapper、ページングPageHelperプラグイン

7228 ワード

TKmybatisは、各mapperに対してsql文を書く必要がなく、汎用mapper呼び出しの対応するインタフェースを継承して単一テーブルの削除変更を完了する汎用mapperを提供します.
統合汎用MAPPER、ページングカード
远虑なく言って、この通用のMapperを使って甚だしきに至ってはあなたのMybatisの単表の基础の操作に対して不便な考えを変えることができて、それを使ってあなたは简単に単表の添削を使うことができて、ダイナミックな添削を含むことができます.
Maven依存の追加またはJarパッケージの導入
Mavenを使用する場合は、次の依存を追加するだけです.


    tk.mybatis
    mapper-spring-boot-starter
    1.1.3




    com.github.pagehelper
    pagehelper-spring-boot-starter
    1.1.2


SQLデータ準備
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '  id',
  `user_name` varchar(32) DEFAULT NULL COMMENT '   ',
  `user_pwd` varchar(32) DEFAULT NULL COMMENT '  ',
  `user_sex` varchar(32) DEFAULT NULL,
  `nick_name` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;

entity
package com.pingkeke.springBoot.entity;

import com.pingkeke.springBoot.enums.UserSexEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import javax.persistence.*;

/**
 * User.
 * @Data
 @ToString、 @EqualsAndHashCode、 @Getter、 @Setter   @RequiredArgsConstructor      。

 @NoArgsConstructor
     ,@NoArgsConstructor              ;

 @AllArgsConstructor
 @AllArgsConstructor                。

 @Accessors         
 chain      
 fluent      
 prefix           getter setter  ,     getter setter        
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)  //       
    @Column(name = "id")
    private Integer id;

    private String userName;
    private String userPwd;
    private UserSexEnum userSex;
    private String nickName;

}

UserMapper
package com.pingkeke.springBoot.util;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * MyMapper.
 */
public interface MyMapper extends Mapper, MySqlMapper {
}
package com.pingkeke.springBoot.mapper;

import com.pingkeke.springBoot.entity.User;
import com.pingkeke.springBoot.util.MyMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

/**
 *      Mapper,      
 *      Mapper,   Mapper           :

 */
@Mapper
public interface UserMapper extends MyMapper {

    @Select("select * from user where user_name=#{username}")
    User selectByName(String username);
}


application.properies
spring.datasource.url=jdbc:mysql://localhost:3306/tdf_db?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#      
mybatis.type-aliases-package=com.pingkeke.springBoot.entity
#Mapper.xml      
mybatis.mapper-locations=classpath:mapper/*.xml
#    
mybatis.configuration.mapUnderscoreToCamelCase=true
#Mapper.xml      
#mybatis.config-locations=classpath:mybatis/mybatis-config.xml
#mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

#tkmapper    
mapper.mappers=com.pingkeke.springBoot.util.MyMapper
mapper.not-empty=false
mapper.identity=MYSQL
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

テスト
package com.pingkeke.springBoot.mapper;

import com.github.pagehelper.PageHelper;
import com.pingkeke.springBoot.entity.User;
import com.pingkeke.springBoot.enums.UserSexEnum;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * UserMapperTest.
 */

@RunWith(SpringRunner.class)
@SpringBootTest
@MapperScan("com.pingkeke.springBoot.mapper")
public class UserMapperTest {
    @Autowired
    private UserMapper userMapper;

    /**
     *        insert
     *       
     *   Oracle  ,UUID,  Mysql INDENTITY    (    )
     *           ,     ,      、UUID,    
     */
    @Test
    public void testInsert() throws Exception {

        User user = new User(null,"bobby1","123",UserSexEnum.MAN,"Bobby1");

        userMapper.insert(user);

        Assert.assertEquals(6, userMapper.selectAll().size());
    }

    /**
     *    selectByName  
     */
    @Test
    public void testSelectByName(){
        User user = userMapper.selectByName("Bobby");

        System.out.println(user.getUserName());
        System.out.println(user.getUserPwd());

        Assert.assertNotEquals(null,user);
    }

    /**
     * selectAll
     * @throws Exception
     */
    @Test
    public void testQuery() throws Exception {

        /**
         * Mapper       ,        。
         */
        PageHelper.startPage(1, 2);

        List users = userMapper.selectAll();

        System.out.println(users.size());

        if(users==null || users.size()==0) {
            System.out.println("is null");
        } else {
            System.out.println(users.toString());
        }
    }


    /**
     * selectByPrimaryKey         
     *         ,        
     *         ,         
     *      ,key      ,    Map
     */
    @Test
    public void testSelectByPrimaryKey() {

        User user = userMapper.selectByPrimaryKey(1);

        System.out.println(user.getUserName());
        System.out.println(user.getUserPwd());

        Assert.assertNotEquals(null,user);
    }

    /**
     *      selectCount
     *        null       ,      = and  
     */
    @Test
    public void testSelectCount() {
        int cnt = userMapper.selectCount(new User());
        System.out.println(cnt);
    }


    /**
     * updateByPrimaryKey
     *         ,            ;
     *       
     * @throws Exception
     */
    @Test
    public void testUpdate() throws Exception {
        User user = userMapper.selectByPrimaryKey(1);

        System.out.println(user.toString());

        user.setNickName("Bobby");
        userMapper.updateByPrimaryKey(user);

        Assert.assertTrue(("Bobby".equals(userMapper.selectByPrimaryKey(1).getNickName())));
    }

    /**
     *        deleteByPrimaryKey
     */
    @Test
    public void testDeleteByPrimaryKey() {
        int cnt = userMapper.deleteByPrimaryKey(28);
        System.out.println(cnt);
    }

}

参考資料
  • MyBatis汎用Mapper
  • MyBatisページングプラグインPageHelper