SprintBoot整合MyBatis简易教程

SprintBoot整合MyBatis简易教程

MyBatis导入及配置

  • 使用Maven管理
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
  • 需要在启动主类添加@MapperScan 使得Mapper文件被扫描到
    即添加下面这行代码到启动主类中,com.imoor.dataobject.mapper为mapper所在包
    @MapperScan(basePackages = "com.imooc.dataobject.mapper")
@SpringBootApplication
@MapperScan(basePackages = "com.imooc.dataobject.mapper")
public class SellApplication {

    public static void main(String[] args) {
        SpringApplication.run(SellApplication.class, args);
    }
}
  • 在控制台打印出MyBatis的sql语句
    application.yml配置文件上配置
logging:
  level:
    com.imooc.dataobject.mapper:trace

将mapper包下的所有类的日志等级设置为最低的trace等级

MyBatis基本操作

package com.imooc.dataobject.mapper;

import com.imooc.dataobject.ProductCategory;
import org.apache.ibatis.annotations.*;

import java.util.List;
import java.util.Map;

//采用MyBatis操作数据库
public interface ProductCategoryMapper {

    //使用Map插入数据
    //注意!!! #{categoryName,jdbcType=VARCHAR} map中的键值需要与categoryName保持一致
    //即map.put("categoryName","testName")
    //jdbcType=VARCHAR是规定写法,jdbcType后面的类型一定要全部大写!!!(只有传入Map对象作为参数,jdbcType才是必写的)
    @Insert("insert into product_category(category_name,category_type) values (#{categoryName,jdbcType=VARCHAR},#{categoryType,jdbcType=INTEGER})")
    int insertByMap(Map<String,Object> map);

    //使用对象插入数据
    //注意!!!  #{categoryName,jdbcType=VARCHAR}    categoryName一定要与ProductCategory类中的属性名称一致
    //且ProductCategory中属性的get和set方法一定要有
    @Insert("insert into product_category(category_name,category_type) values (#{categoryName},#{categoryType})")
    int insertByObject(ProductCategory productCategory);

    //查询结果只有单条
    //注意!!! 查询需要返回结果,格式如下,column的值为数据库中的字段名,而property的值为对应类的属性名
    @Select("select * from product_category where category_type = #{categoryType}")
    @Results({
            @Result(column = "category_type",property = "categoryType"),
            @Result(column = "category_name",property = "categoryName"),
            @Result(column = "category_id",property = "categoryId"),

    })
    ProductCategory findByCategoryType(Integer categoryType);

    //查询结果有多个
    //注意!!! 查询需要返回结果,格式如下,column的值为数据库中的字段名,而property的值为对应类的属性名
    @Select("select * from product_category where category_name = #{categoryName}")
    @Results({
            @Result(column = "category_type",property = "categoryType"),
            @Result(column = "category_name",property = "categoryName"),
            @Result(column = "category_id",property = "categoryId"),

    })
    List<ProductCategory> findByCategoryName(String categoryName);

    //更新
    //注意!!! 传多个参数时需要使用@Param映射一下
    @Update("update product_category set category_name=#{categoryName} where category_type=#{categoryType}")
    int updateByCategoryType(@Param("categoryName") String categoryName,@Param("categoryType") Integer categoryType);


    //使用对象更新
    @Update("update product_category set category_name=#{categoryName} where category_type=#{categoryType}")
    int updateByObject(ProductCategory productCategory);

    //删除数据
    @Delete("delete from product_category where category_type = #{categoryType}")
    int deleteByCategoryType(Integer categoryType);
}

对应测试代码


package com.imooc.dataobject.mapper;

import com.imooc.dataobject.ProductCategory;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class ProductCategoryMapperTest {

    @Autowired
    private ProductCategoryMapper mapper;
    @Test
    public void insertByMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("category_name","fine");
        map.put("category_type",90);
        int result = mapper.insertByMap(map);
        Assert.assertNotEquals(0,result);
    }
    @Test
    public void insertByObject(){
        ProductCategory productCategory = new ProductCategory();
        productCategory.setCategoryId(30);
        productCategory.setCategoryName("testName");
        productCategory.setCategoryType(100);
        int result = mapper.insertByObject(productCategory);
        Assert.assertNotEquals(0,result);
    }

    @Test
    public void findByCategoryTypeTest(){
        ProductCategory productCategory = mapper.findByCategoryType(3);
        Assert.assertNotNull(productCategory);
    }

    @Test
    public void findByCategoryNameTest(){
        List<ProductCategory> resultList = mapper.findByCategoryName("food");
        Assert.assertNotEquals(1,resultList.size());
    }

    @Test
    public void updateByCategoryTypeTest(){
        int result = mapper.updateByCategoryType("helloTest", 11);
        Assert.assertEquals(1,result);
    }

    @Test
    public void updateByObjectTest(){
        ProductCategory productCategory = new ProductCategory();
        productCategory.setCategoryName("worldTest");
        productCategory.setCategoryType(11);
        int result = mapper.updateByObject(productCategory);
        Assert.assertEquals(1,result);
    }

    @Test
    public void deleteByCategoryTypeTest(){
        int result = mapper.deleteByCategoryType(11);
        Assert.assertNotEquals(0,result);
    }
}

猜你喜欢

转载自blog.csdn.net/tubro2017/article/details/84950258
今日推荐