开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第9天,点击查看活动详情
mybatis-plus插件整合
1.pom.xml引入依赖
<!-- mybatis plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.3.2</version>
</dependency>
2.修改applicationContext.xml配置
<bean id="sessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
代码说明:
bean id:不变
class:改成mybatis-plus扩展
3.mybatis-config.xml新增分页插件
<plugins>
<plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor"></plugin>
</plugins>
4.新增entity包
package com.imooc.reader.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("test")//对应的表
public class Test {
@TableId(type = IdType.AUTO) //自增主键ID
@TableField("id")
private Integer id; //对应的id字段
@TableField("content")
private String content;//对应的content字段
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
代码说明:
@TableName("test"):对应的表名
@TableField("id"):对应的数据库字段ID
@TableId(type = IdType.AUTO):对应数据表字段的自增ID
定义字段:创建getter和setter方法
5.mapper新增对应的TestMapper文件
package com.imooc.reader.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.imooc.reader.entity.Test;
public interface TestMapper extends BaseMapper<Test> {
public void insertSample();
}
代码说明:
extends BaseMapper:继承BaseMapper
Test:定义泛型,传入实体类
6.新增MyBatisPlusTest测试文件
引入@Resource TestMapper
@Resource
private TestMapper testMapper;
新增数据
@org.junit.Test
public void testInsert(){
Test test = new Test();
test.setContent("测试新增");
testMapper.insert(test);
}
修改数据
@org.junit.Test
public void testUpdate(){
Test test = testMapper.selectById(47);
test.setContent("batis");
testMapper.updateById(test);
}
代码说明:
Test test = testMapper.selectById(47);先进行查询
test.setContent():设置属性
testMapper.updateById(test);:调用更新方法
删除数据
@org.junit.Test
public void testDelete(){
testMapper.deleteById(47);
}
代码说明:
testMapper.deleteById(47):根据主键ID删除对应的数据
查询数据
@org.junit.Test
public void testSelect(){
QueryWrapper<Test> queryWrapper = new QueryWrapper<Test>();
queryWrapper.eq("id",45);
List<Test> list = testMapper.selectList(queryWrapper);
System.out.println(list.get(0));
}
代码说明: QueryWrapper queryWrapper = new QueryWrapper(); 查询数据需要在QueryWrapper传入泛型