Spring Boot 集成mybatis(gradle)

集成mybatis

[toc]
简书不支持目录,截图。

《Spring Boot 集成mybatis(gradle)》 image.png

mybatis 注解方式

  • 第一步:引入依赖包: build.gradle

    buildscript {
        ext {
            springBootVersion = '1.5.4.RELEASE'
        }
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        }
    }
    
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'org.springframework.boot'
    
    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = 1.8
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compile('org.springframework.boot:spring-boot-starter')
        testCompile('org.springframework.boot:spring-boot-starter-test')
        
        compile 'mysql:mysql-connector-java'
        
        //配置mybatis 数据源
        compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0")
        testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.0')
        
        //使用 Controller 的时候需要引入 web 包
        compile('org.springframework.boot:spring-boot-starter-web')
    }
    
  • 第二步:数据库连接配置 application.yml

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
        username: root
        password: root
    
  • 第三步:增加包扫描 Mapper 文件,也可以在 xml 文件中配置,以下使用注解。

    @SpringBootApplication
    @MapperScan("com.example.demo.dao.mapper")
    public class App {
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
    
  • 第四步:写 Mapper 接口,使用 mybatis 的注解

    public interface UserMapper {
    
        @Select("select * from person where id = #{id}")
        Person findByID(Integer id);
    
        //返回的Integer值是变化的行数,@Options()会填充到实体 person 中。
        @Insert("insert into person(name, age) values(#{name}, #{age})")
        @Options(useGeneratedKeys = true, keyProperty = "id")
        Integer addPerson(Person person);
    
    //    @Insert("insert into person(name, age) values(#{name}, #{age})")
    //    Integer addPerson(@Param("name") String name, @Param("age") Integer age);
    
        @Update("update person set name = #{name}, age = #{age} where id = #{id}")
        Integer updatePerson(@Param("name") String name, @Param("age") Integer age, @Param("id") int id);
    
        @Delete("delete from person where id = #{id}")
        Integer deletePerson(Integer id);
    
        @Select("select * from person")
        List<Person> findAllPage();
    
    }
    

mybatis xml方式

  • 第一步:引入依赖包: build.gradle

    buildscript {
        ext {
            springBootVersion = '1.5.4.RELEASE'
        }
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        }
    }
    
    apply plugin: 'java'
    apply plugin: 'eclipse'
    apply plugin: 'org.springframework.boot'
    
    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = 1.8
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compile('org.springframework.boot:spring-boot-starter')
        testCompile('org.springframework.boot:spring-boot-starter-test')
        
        compile 'mysql:mysql-connector-java'
        
        //配置mybatis 数据源
        compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0")
        testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.0')
        
        //使用 Controller 的时候需要引入 web 包
        compile('org.springframework.boot:spring-boot-starter-web')
    }
    
  • 第二步:数据库连接配置 application.yml

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
        username: root
        password: root
        
    mybatis:
        type-aliases-package: org.larry.springboot.entity
        mapper-locations: classpath:mapper/**/*.xml
        check-config-location: true
    
  • 第三步:配置包扫描 Mapper 文件 Application.java

    @SpringBootApplication
    @MapperScan("com.example.demo.mapper")
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
  • 第四步:测试代码

    创建model 和 Mapper 文件用于测试,但是可以使用 generator 自动生成。

    public class User {
        private Integer id;
    
        private String name;
    
        public User(Integer id, String name) {
            this.id = id;
            this.name = name;
        }
    
        public User() {
            super();
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name == null ? null : name.trim();
        }
    }
    
    public interface UserMapper {
        long countByExample(UserExample example);
    
        int deleteByExample(UserExample example);
    
        int deleteByPrimaryKey(Integer id);
    
        int insert(User record);
    
        int insertSelective(User record);
    
        List<User> selectByExample(UserExample example);
    
        User selectByPrimaryKey(Integer id);
    
        int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
    
        int updateByExample(@Param("record") User record, @Param("example") UserExample example);
    
        int updateByPrimaryKeySelective(User record);
    
        int updateByPrimaryKey(User record);
    
        @Select("select * from user")
        List<User> findAll();
    }
    
    @RestController
    public class UserContorller {
    
        @Autowired
        private UserMapper userMapper;
    
        @RequestMapping("/insert")
        public User insertUser() {
            User user = new User(null, "inke");
            userMapper.insert(user);
            return user;
        }
    
        @RequestMapping("/findAll")
        public List<User> findAll() {
            return userMapper.findAll();
        }
    }
    

分页查询 pagehelper

  • 第一步:引入依赖包: build.gradle

    dependencies {
        compile('org.springframework.boot:spring-boot-starter')
        testCompile('org.springframework.boot:spring-boot-starter-test')
        compile 'org.springframework.boot:spring-boot-devtools'
     
        compile 'mysql:mysql-connector-java'
        
        //配置mybatis 数据源
        compile("org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.0")
        testCompile('org.mybatis.spring.boot:mybatis-spring-boot-starter-test:1.3.0')
        //pagehelper
        compile("com.github.pagehelper:pagehelper-spring-boot-starter:1.1.1")
        //mapper 使用 xml 的 mybatis 方式,需要引入下面的包,不然 dev-tools 会报错
        //compile("tk.mybatis:mapper-spring-boot-starter:1.1.1")
    }
    
  • 第二步:数据库连接配置 application.yml

    server:
      port: 9010
    
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8
        username: root
        password: root
    
    mybatis:
        type-aliases-package: tk.mybatis.springboot.model
        mapper-locations: classpath:mapper/*.xml
    
    #mapper:
    #    mappers:
    #        - tk.mybatis.springboot.util.MyMapper
    #    not-empty: false
    #    identity: MYSQL
    
    pagehelper:
        helperDialect: mysql
        reasonable: true
        supportMethodsArguments: true
        params: count=countSql
    
  • 第三步:测试代码

    @Test
    public void testFindAllPage() {
       // startPage(pageNum, pageSize);
       PageHelper.startPage(1, 3);
       List<Person> persons = userMapper.findAllPage();
       System.out.println("findAllPage:" + persons);
       PageInfo<Person> pageInfo = new PageInfo<>(persons);
       System.out.println("pageInfo:" + pageInfo);
       //获取返回的数据
       List<Person> lists = pageInfo.getList();
       for (Person person : lists) {
           System.out.println("person:" + person);
       }
    }
    
    原文作者:inke
    原文地址: https://www.jianshu.com/p/b0cf9c476d7b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞