提要
这里已经将Springboot环境创建好 这里只是整合MyBatis过程
引入Maven依赖
添加MyBatisPlus启动依赖,添加mysql-connector-java依赖
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!-- mybatis-plus代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<!-- mysql连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
添加application.yml配置
mybatis-plus配置项
mybatis-plus:
# xml文件路径
mapper-locations: classpath:mapper/*.xml
# 实体类路径
type-aliases-package: com.数据库表对应的实体类的路径
configuration:
# 驼峰转换
map-underscore-to-camel-case: true
# 是否开启缓存
cache-enabled: false
# 打印sql
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 全局配置
global-config:
# 数据库字段驼峰下划线转换
db-column-underline: true
# id自增类型(数据库id自增)
id-type: 0
mysql配置项
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://ip:3306/库名?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
添加数据库对应实体类
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("s_user")
public class UserEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String userName;
private Integer sex;
}
添加Mapper文件
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.service.servicea.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {
}
添加Service
(这里我没有用service接口及实现)
import com.service.servicea.dao.UserMapper;
import com.service.servicea.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public UserEntity getUserById(Long id) {
return userMapper.selectById(id);
}
}
添加Controller
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/selectUser")
public ResponseEntity<UserEntity> getUser(Long id) {
UserEntity userEntity = userService.getUserById(id);
return ResponseEntity.ok(userEntity);
}
}
补充对应表结构
CREATE TABLE `s_user` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'id',
`user_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户名',
`sex` int DEFAULT '0' COMMENT '性别0男1女',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='用户表';
如果本文对你有帮助,别忘记给我个3连 ,点赞,转发,评论,,咱们下期见。