目录
1.添加依赖到pom
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<!--lombok用来简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2.新建数据表
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)
);
插入数据
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');
查看结果
3.整合mybatis
先来看看目录结构
entity:放置实体化类
mapper:实体化的mapper类接口
配置数据库连接,我这里用的yml文件用properties也是一样的
如果有多个配置文件要在默认的配置文件下引入其他配置文件,application.yml最好有不然可能会有莫名其妙的bug
application.yml
server:
port: 8083
#引入其他yml文件
spring:
profiles:
active: datasource,test
groovy:
template:
cache: false
com:
example:
mes: wyt!!!!aiaiai
application-datasource.yml
boot_crm是 数据库的名字找到自己对应的
如果数据库在8.0以上要在driver加 cj
用户对应自己的用户名和密码
spring:
dataSource:
url: jdbc:mysql://localhost:3306/boot_crm?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Hongkong
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
在entity包下新建User类
package com.example.springdemo.entity;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge(int i) {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private String email;
}
mapper包下新建UserMapper接口
package com.example.springdemo.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springdemo.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper extends BaseMapper<User> {
}
在控制类添加包扫描扫描mapper层
@MapperScan("com.example.springdemo.mapper")
测试类
引入UserMapper
@Autowired
UserMapper userMapper;
@Test
void testMybatisPlus(){
List<User> users=userMapper.selectList(null);
for (User user:users){
System.out.println(user);
}
System.out.println("查询成功!");
User aduuser=new User();
aduuser.setName("DFP");
aduuser.setAge(18);
aduuser.setEmail("DFP19053025@qq.com");
aduuser.setId(19053065L);
int i=userMapper.insert(aduuser);
if (i>0){
System.out.println("成功加入记录!");
}else{ System.out.println("失败加入记录!");}
for (User user:users){
System.out.println(user);
}
}
查看结果控制台和数据库