一、添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!--LomBok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <optional>true</optional>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
二、配置数据源
在配置文件application.yml中配置数据源
spring:
# 配置数据源信息
datasource:
# 配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
# 配置连接数据库信息
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/spring_demo?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
三、在启动类上扫描dao的路径
四、创建实体并与数据库表关联
package demo.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data//生成Get和Set方法,重写toString
@AllArgsConstructor//生成有参构造器
@NoArgsConstructor//生成无参构造器
@TableName("s_user")//设置表名
public class User {
@TableId//指定主键id
private Long id;
@TableField("name")//当命名无法规范时指定表头
private String name;
private String sex;
}
五、创建dao继承自BaseMapper
package demo.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import demo.entity.User;
public interface userDao extends BaseMapper<User> {
}
六、在controller中测试
第1步:通过AutoWired注解实例化dao对象
public class TestController {
@Autowired(required = false)
private userDao dao;
第2步:调用dao方法实现增删改查
增
@RequestMapping("/aaa")
public int insertUser(){
int count = dao.insert(new User(null,"张飒","男"));
return count;
}
删
//根据id删除
@RequestMapping("/bbb")
public int delete(){
int count = dao.deleteById("1592371787249790978");
return count;
}
改
//根据id修改
@RequestMapping("/ee")
public int updateById(){
int count = dao.updateById(new User(1592406249895366657L, "王德发", "男"));
return count;
}
查
//查询全部
@RequestMapping("/ccc")
public List<User> selectList(){
List<User> list = dao.selectList(null);
return list;
}
//根据id查询
@RequestMapping("/dd")
public User selectById(){
User user = dao.selectById(1592400768451743745L);
return user;
}