mybatis-plus需要两个依赖,一个lombok,一个mybatis-plus
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version>
</dependency>
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>
package com.learn.mybatisplus.pojo;
import lombok.*;//lombok快速创建实体类
//@Data=无参构造+getter+setter+hash+toString
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@EqualsAndHashCode@Data
@TableName("user")
public class User {private long id;private Integer age;private String name;private String email;}
mapper继承BaseMapper即可
basemapper中封装了很多方法,如userMapper.selectList
// 标识为持久层组件
@Repository
public interface UserMapper extends BaseMapper<User> {}
@SpringBootTest
public class MyBatisPlusTest {@Autowiredprivate UserMapper userMapper;@Testpublic void testSelctList() {// 通过条件构造器查询一个List集合,若没有条件则设置wrapper条件为nullList<User> list = userMapper.selectList(null);list.forEach(System.out::println);}
}
//配置文件中配置在日志中输出mybatis-plus生成的sql
mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
通过userMapper的方法实现增删改查
@Testpublic void testInsert() {User user = new User();user.setAge(24);user.setEmail("wxs@qq.cn");user.setName("王xs");int result = userMapper.insert(user);System.out.println("result = " + result);System.out.println("id = " + user.getId());}@Testpublic void testDelete() {//int result = userMapper.deleteById(1674710493506195458L);//System.out.println("result = " + result);Map<String, Object> map = new HashMap<>();map.put("name", "张三");map.put("age",23);int result = userMapper.deleteByMap(map);//执行的sql:DELETE FROM user WHERE name = ? AND age = ?System.out.println(result);//通过idList批量删除List<Long> list = Arrays.asList(1L, 2L, 3L);int result = userMapper.deleteBatchIds(list);System.out.println("result = " + result);@Testpublic void testUpdate() {User user = new User();user.setId(4L);user.setName("李四");user.setEmail("lisi@qq.com");int result = userMapper.updateById(user);//执行的sql:UPDATE user SET name=?, email=? WHERE id=?System.out.println(result);}