如何使用SpringBoot整合Mybatis——注解方式


一、介紹

SpringBoot有兩種方法來整合Mybatis,一種是XML文件配置方式,另一種是注解方式,主要優勢點如下:

  • XML配置方式:隔離sql和業務代碼,能夠更為清晰地表達sql,尤其是對於較長的sql代碼;
  • 注解方式:代碼更為精簡,方便。

本文主要討論如何用注解方式來整合Mybatis。

二、實現

新建SpringBoot項目

新建一個SpringBoot項目,這個很簡單,這里不再贅述。

導入相關依賴

由於要整合Mybatis,所有我們需要在項目的配置文件pom.xml中添加mysql和mybatis依賴:

<!--mysql依賴-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis依賴-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
</dependency>

准備數據庫

  1. 數據庫的創建
    准備一個測試用的product_Category表,其中有category_idcategory_namecategory_type三個屬性,其中category_id為主鍵且自增,然后可以插入一些數據。
CREATE TABLE `product_category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `category_name` varchar(64) NOT NULL COMMENT '類目名字',
  `category_type` int(11) NOT NULL COMMENT '類目編號',
  PRIMARY KEY (`category_id`),
  UNIQUE KEY `uqe_category_type` (`category_type`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COMMENT='類目表';

INSERT INTO product_category values (1,"熱銷榜",2);
INSERT INTO product_category values (2,"熱評榜",1);


2. 在項目配置文件application.yml中配置數據源:

# 數據庫配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://10.3.11.185/sell?characterEncoding=utf-8&useSSL=false

新建實體類層

根據數據庫創建實體類。為了精簡代碼,后面大多使用了Lombok插件,比如使用@Data注解,需要事先下載Lombok插件,然后在pom.xml引入依賴:

<!--導入Lombok依賴-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

//productCategory實體類
@Entity
@Data
public class ProductCategory {
    //類目id
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) //主鍵自增
    private Integer categoryId;

    //類目名字
    private String categoryName;

    //類目編號
    private Integer categoryType;
}

編寫實體類對應接口,在這里就可以直接使用注解寫sql語句了

這里模擬使用mybatis對類目進行增刪改查:

public interface ProductCategoryMapper {

    //方法一:以Map的方式插入(注意values中的寫法,要指定數據類型)
    @Insert("insert into product_category(category_name,category_type) values (#{category_name,jdbcType=VARCHAR},#{category_type,jdbcType=INTEGER})")
    int insertByMap(Map<String,Object> map);

    //方法二:以對象的方式插入
    @Insert("insert into product_category(category_name,category_type) values (#{categoryName,jdbcType=VARCHAR},#{categoryType,jdbcType=INTEGER})")
    int insertByObject(Object object);

    @Select("select * from product_category where category_type = #{categoryType}")
    @Results({
            @Result(column = "category_id", property = "categoryId"),
            @Result(column = "category_name", property = "categoryName"),
            @Result(column = "category_type", property = "categoryType"),
    })
    ProductCategory findByCategoryType(Integer categoryType);

    @Select("select * from product_category where category_name = #{categoryName}")
    @Results({
            @Result(column = "category_id", property = "categoryId"),
            @Result(column = "category_name", property = "categoryName"),
            @Result(column = "category_type", property = "categoryType"),
    })
    List<ProductCategory> findByCategoryName(String categoryName);

    @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(Object object);

    @Delete("delete from product_category where category_type = #{categoryType}")
    int deleteByCategoryType(Integer categoryType);

}

配置Mapper掃描的路徑

要想程序正常運行,還需要讓程序知道Mapper文件的位置,需要配置Mapper掃描的路徑。在啟動的主類上添加@MapperScan注解,basePackages屬性值即為剛才寫的實體類對應接口的路徑:

@SpringBootApplication
@MapperScan(basePackages = "com.imooc.dataobject.mapper")
public class SellApplication {
    public static void main(String[] args) {
        SpringApplication.run(SellApplication.class, args);
    }
}

對實體類對應接口進行單元測試:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Slf4j
class ProductCategoryMapperTest {

    @Autowired
    private ProductCategoryMapper mapper;

    @Test
    public void insertByMap() throws Exception{
        Map<String,Object> map = new HashMap<>();
        map.put("category_name","可口可樂");
        map.put("category_type",12);
        int result = mapper.insertByMap(map);
        Assert.assertEquals(1,result);
    }

    @Test
    public void insertByObject() throws Exception{
        ProductCategory productCategory = new ProductCategory();
        productCategory.setCategoryName("雪碧");
        productCategory.setCategoryType(14);
        int result = mapper.insertByObject(productCategory);
        Assert.assertEquals(1,result);
    }

    @Test
    public void findByCategoryType(){
        ProductCategory result = mapper.findByCategoryType(12);
        Assert.assertNotNull(result);
    }

    @Test
    public void findByCategoryName(){
        List<ProductCategory> result = mapper.findByCategoryName("雪碧");
        Assert.assertNotEquals(0,result.size());
    }

    @Test
    public void updateByCategoryType(){
        int result = mapper.updateByCategoryType("雪小碧",14);
        Assert.assertEquals(1,result);
    }

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

    @Test
    public void deleteByCategoryType(){
        int result = mapper.deleteByCategoryType(14);
        Assert.assertEquals(1,result);
    }
}

可以發現數據庫中的數據被更新了:

再對應寫Service層代碼

Service接口:

public interface CategoryService {

    int insertByMap(Map<String,Object> map);

    ProductCategory findByCategoryType(Integer categoryType);

    List<ProductCategory> findByCategoryName(String categoryName);

    int updateByCategoryType(String categoryName,Integer categoryType);
    
    int deleteByCategoryType(Integer categoryType);
}

Service接口實現類CategoryServiceImpl:

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private ProductCategoryMapper mapper;

 
    @Override
    int insertByMap(Map<String,Object> map){
        return mapper.insertByMap(map);
    }

    @Override
    ProductCategory findByCategoryType(Integer categoryType){
        return mapper.findByCategoryType(categoryType);
    }

    ...
    ...
    ...
}

9. 對應寫Controller層代碼

@Controller
@RequestMapping("/seller/category")
public class SellerCategoryController {

    @Autowired
    private CategoryService categoryService;

    // 類目列表
    @GetMapping("/list")
    public ProductCategory findByCategoryType(@RequestParam(value = "categoryType") Integer categoryType){
        ...
    }

    ...
    ...
    ...
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM