MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
全新的 MyBatis-Plus 3.0 版本基于 JDK8,提供了 lambda 形式的调用,所以安装集成 MP3.0 要求如下:
ID | Name | Sex | Age | Grade |
1 | 小明 | 男 | 12 | 6 |
2 | 小红 | 女 | 11 | 6 |
建表语句如下:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`
(
id BIGINT NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
sex VARCHAR(30) NULL DEFAULT NULL COMMENT '性别',
age INT NULL DEFAULT NULL COMMENT '年龄',
grade VARCHAR(50) NULL DEFAULT NULL COMMENT '年级',
PRIMARY KEY (id)
);
然后插入数据:
INSERT INTO `user` (id, name, age, email) VALUES
(1, '小明', '男',12, 6),
(2, '小红', '女',11, 6),
org.springframework.boot
spring-boot-starter-parent
3.1.5
org.springframework.boot
spring-boot-starter
com.h2database
h2
runtime
com.baomidou
mybatis-plus-spring-boot3-starter
3.5.4
mysql
mysql-connector-java
8.0.26
在application.yaml
中配置相关配置信息:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/Doker
username: root
password: root
@Data
@TableName("`user`")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
@TableField("name")
private String name;
private String sex;
private Integer age;
private String grade;
}
TableName:
TableId:
TableField:
UserMapper
接口
SELECT * FROM `user` WHERE `name` = #{name}
public interface UserMapper extends BaseMapper {
@Select("select * from user")
List getAllUser();
}
import com.baomidou.mybatisplus.extension.service.IService;
// UserService 继承 IService 接口
public interface UserService extends IService{
List getAllUser();
}
@Service
public class UserServiceImpl extends ServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public List getAllUser()
{
return userMapper.getAllUser();
}
}
@MapperScan
注解,扫描 Mapper 文件夹:@SpringBootApplication
@MapperScan("com.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}