1. mybatis-plus概述
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
不能替代mybatis ,以后对于单表操作的所有功能,都可以使用mp完成。但是链表操作的功能还得要校验mybatis.
2. 如何使用mp
(1)创建表并插入数据
DELETE FROM user;
INSERT INTO user (smpno, sname, sno) VALUES
(1, 'Jone', 18 ),
(2, 'Jack', 20 ),
(3, 'Tom', 28 ),
(4, 'Sandy', 21 ),
(5, 'Billie', 24 );
(2)引入相关依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
(3)在.properties文件下配置数据源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://locaLhost:3306/mybatis_db
spring.datasource.username=root
spring.datasource.password=123456
(3) 创建实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student implements Serializable {
/**
*
*/
@TableId(type = IdType.AUTO)
private Integer smpno;
/**
*
*/
private String sname;
/**
*
*/
private Integer sno ;
}
(5)创建一个Mapper接口
public interface Studentmapper extends BaseMapper<Student> {
}
(6)为接口生成代理实现类,在启动类上加上注解
@MapperScan(basePackages = "这里写Mapper包路径")
@SpringBootApplication
@MapperScan(basePackages = "com.example.demo.mapper")
public class Demo4Application {
public static void main(String[] args) {
SpringApplication.run(Demo4Application.class, args);
}
}
(7)测试
@SpringBootTest
class Demo4ApplicationTests {
@Autowired
private Studentmapper studentmapper;
//通过Id查询
@Test
void contextLoads(){
Student student = studentmapper.selectById(1);
System.out.println(student);
}
}
3.总结
1.引入mp依赖 2. 在.properties文件里创建数据源 3. 创建实体类 4.创建mapper接口并继承BaseMapper<>接口 5.在启动类接口扫描 6.测试