Springboot使用Mybatis-plus的BaseMapper
主要记录两个知识点
- Mabatis-plus的不使用Mapper.xml
- 使用@Mapper注解和不使用注解@Mapper,使用启动类(@MapperScan)扫描两种方法
pom.xml
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/testMyBatisPlus?useUnicode=true&characterEncoding=utf8
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
实体类
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("test_table")
public class Table {
private Long id;
private String name;
}
Mapper.java
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hong.bean.Table;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 如果不使用注解,需要启动类扫描mapper.java文件位置
// @Mapper
public interface TableMapper extends BaseMapper<Table> {
/*@Select("select * from test_table ")
List<Table> all();*/
}
启动类
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.hong.dao")
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Test
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hong.bean.Table;
import com.hong.dao.TableMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TableTest {
// 启动类使用注解扫描后,这里还是会爆红,但不影响调用
// 为什么要在启动类扫描,不用注解,这么做是可以使每个Mapper.java都不添加注解@Mapper
@Autowired
private TableMapper mapper;
@Test
public void test() {
// List<Table> all = mapper.all();
// List<Table> all = mapper.selectList(null);
List<Table> all = mapper.selectList(new QueryWrapper<>());
all.forEach(table -> System.out.println(JSONUtil.toJsonStr(table)));
}
}