快速开始
步骤
- 创建数据库: mybatis
现有一张 User 表
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
其对应的数据库 Data 脚本如下:
DELETE FROM user;
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
- 初始化项目
创建一个springboot项目
- 导入依赖
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--lombok用来简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
- 连接数据库
配置application.properties
useSSl=false&nuseUnicode=true&characterEncoding=utf-8
#mysql数据库连接
# mysql 5.0
spring.datasource .driver-class-name = com.mysql.jdbc.Driver
spring.datasource .url = jdbc:mysql:// localhost:3306 / mybatis_plus
spring.datasource .username = root
spring.datasource .password = 123456
# mysql 8.0
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:// localhost:3306 / mybatis_plus ?serverTimezone = GMT%2B8&useSSl=false&nuseUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=2322jiang
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fan.mybatisplus.pojo.User;
import org.springframework.stereotype.Repository;
// 在对应的Mapper上面继承基本的类 BaseMapper
@Repository // 代表持久层
public interface UserMapper extends BaseMapper<User> {
}
@MapperScan("com.fan.mybatisplus.mapper") // 扫描 mapper 文件夹
@SpringBootApplication
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
import com.fan.pojo.User;
import com.fan.pojo.mapper.UserMapper;
import org.apache.catalina.mbeans.UserMBean;
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 MybatisPlusApplicationTests {
// 继承了BaseMapper, 所有的方法都来自父类
// 也可以编写自己的扩展方法!
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
// 查询全部用户
// 参数是一个Wrapper ,条件构造器.
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}