spring-boot集成mybatis-plus
spring-boot集成mybatis-plus
目录
依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
配置
application.properties文件
spring.datasource.url=jdbc:mysql://192.168.111.222:3306/dbname?serverTimezone=Asia/Shanghai&characterEncoding=utf-8&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
启动类添加@Mapper注解
在 Spring Boot 启动类中添加 @MapperScan
注解,扫描 Mapper 文件夹:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.qq.quickstart.mapper")
public class QuickstartApplication {
public static void main(String[] args) {
SpringApplication.run(QuickstartApplication.class, args);
}
}
编码
实体类
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("user")
public class User {
@TableId
private Long id;
private String username;
private String password;
}
Mapper类
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qq.quickstart.entity.User;
import org.apache.ibatis.annotations.Mapper;
//如果启动类上加了@MapperScan,则这里可以不加@Mapper
//@Mapper
public interface UserMapper extends BaseMapper<User> {
}
Service类
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qq.quickstart.entity.User;
import com.qq.quickstart.mapper.UserMapper;
import org.springframework.stereotype.Service;
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
}
测试
@Test测试
import com.qq.quickstart.entity.User;
import com.qq.quickstart.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
class QuickstartApplicationTests {
@Autowired
private UserService userService;
@Test
public void test() {
List<User> list = userService.list();
System.out.println("有数据:" + list.size() + "条");
list.forEach(System.out::println);
}
}
测试结果
控制台打印
有数据:2条
User(id=1, username=admin, password=xxx)
User(id=2, username=test, password=xxx)
参考:
https://baomidou.com/pages/226c21/
https://github.com/baomidou/mybatis-plus-samples/