版权声明:youngPeng原创,看后点赞,知识分享 https://blog.csdn.net/m0_37156901/article/details/85481893
最近学了spring boot 开发微信点餐系统,学到的东西很多,有SSM框架的使用基础,所以对于spring boot + JPA +freeMark,这种开发模式很是喜欢,极大的简化了前后端的繁琐编写,注重业务逻辑,很好用,有了之前SSM框架学习的痛点和坑,在spring boot中又看到注解,很开心,所以想记下来,也是小编第一篇博客。读研学生,没多少实战经验,多多鼓励一下。
废话少说,直接分步骤搞定。
首先mybatis使用方式有两种:
1. 通过注解使用
举个栗子,直接在方法上面使用注解写上接口
@Insert("insert into product_category(category_name, category_type) values(#{categoryName, jdbcType=VARCHAR}, #{categoryType, jdbcType=INTEGER})")
public int insertByObject(ProductCategory productCategory);
2. 通过配置xml文件使用
如果不使用上面接口注解的方式,则建立xml文件,j将所有SQL语句写里面,他要跟一些对象绑定。如图,
第三部:不要忘了配置你的xml文件在哪
上面讲的是mybatis的两种使用方式展示,接下来正式开始使用的步骤
第一步:引入mybatis依赖
<!--mybatis 使用半自动化的注解很方便-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
第二部:在启动类里配置扫描包路径@mapperscan
第三步:不要忘了配置,也就是告诉你的xml文件在哪里
(适用于mybatis第二种使用方式)
要是使用接口加方法方式,则在启动类里面使用@mapperscan()告知
以上主要讲解了如何使用mybatis,以xml方式写mybatis,或者使用注解接口的方式用mybatis,分别给出了图示例,忘了,还要测试,再贴一张测试的图,以便参考。
首先引入写了注解的那个类(是接口的那种方式需要写),然后写测试方法。
@RunWith(SpringRunner.class)
@SpringBootTest
public class ProductCategoryMapperTest {
@Autowired
// 使用ibatis必须在主类中配置 扫描包,告诉mapper在哪里
private ProductCategoryMapper mapper;
@Test
public void insertByMap() {
Map<String, Object> map = new HashMap<>();
map.put("category_name", "mybatisMap 插入测试");
map.put("category_type", 20);
int result = mapper.insertByMap(map);
Assert.assertEquals(1,result);
}
@Test
public void insertByObject(){
ProductCategory productCategory = new ProductCategory();
productCategory.setCategoryName("batisMapperT ");
productCategory.setCategoryType(22);
int result = mapper.insertByObject(productCategory);
Assert.assertEquals(1,result);
}
}