Spring Boot 集成mybatis(gradle)

集成mybatis

[toc]
簡(jiǎn)書不支持目錄,截圖。


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 數(shù)據(jù)源
        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 的時(shí)候需要引入 web 包
        compile('org.springframework.boot:spring-boot-starter-web')
    }
    
  • 第二步:數(shù)據(jù)庫(kù)連接配置 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值是變化的行數(shù),@Options()會(huì)填充到實(shí)體 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 數(shù)據(jù)源
        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 的時(shí)候需要引入 web 包
        compile('org.springframework.boot:spring-boot-starter-web')
    }
    
  • 第二步:數(shù)據(jù)庫(kù)連接配置 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);
        }
    }
    
  • 第四步:測(cè)試代碼

    創(chuàng)建model 和 Mapper 文件用于測(cè)試,但是可以使用 generator 自動(dòng)生成。

    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();
        }
    }
    



分頁(yè)查詢 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 數(shù)據(jù)源
        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 會(huì)報(bào)錯(cuò)
        //compile("tk.mybatis:mapper-spring-boot-starter:1.1.1")
    }
    
  • 第二步:數(shù)據(jù)庫(kù)連接配置 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
    
  • 第三步:測(cè)試代碼

    @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);
       //獲取返回的數(shù)據(jù)
       List<Person> lists = pageInfo.getList();
       for (Person person : lists) {
           System.out.println("person:" + person);
       }
    }
    



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容