MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1. 导入mybatis-plus、lombok、mysql坐标依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
2.application.yml配置文件编写
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot
driver-class-name: com.mysql.jdbc.Driver
username: root
password: 111111
logging:
level:
com.zyw.mydemo.mapper: debug
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.在springboot入口类加上mapper包扫描
@MapperScan("com.zyw.mpdemo.mapper")
4.实体类:
这里使用lombok的注解@Data实现自动注入getter 、setter
这里插入的id当插入时使用雪花算法生成,如果要使用自增id或者别的需要加注解@TableId(type=IdType.AUTO)
实现。
@Data
public class Account {
private Long id;
private String name;
private Double money;
}
5.mapper 只需要继承BaseMapper就可以,然后传入实体类
@Repository
public interface AccountMapper extends BaseMapper<Account> {
}
6.service
public interface AccountService {
public List<Account> findAll();
public void addAccount(Account account);
}
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public List<Account> findAll() {
return accountMapper.selectList(null);
}
@Override
public void addAccount(Account account) {
accountMapper.insert(account);
}
}
7.controller
@RestController
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public List<Account> findAll(){
return accountService.findAll();
}
@RequestMapping("/addAccount")
public void addAccount(Account account){
accountService.addAccount(account);
}
}
测试查询:
插入:
雪花算法自动生成了19位的id值。
帮助到您请点赞关注收藏谢谢!!