Springboot 整合 MyBatisPlus[詳細過程] 提要 這裡已經將Springboot環境創建好 這裡只是整合MyBatis過程 引入Maven依賴 添加MyBatisPlus啟動依賴,添加mysql-connector-java依賴 <!-- mybatis-plus --> <de ...
Springboot 整合 MyBatisPlus[詳細過程]
提要
這裡已經將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: stone
url: jdbc:mysql://ip:3306/庫名?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false
添加資料庫對應實體類
@Data
@TableName("class_table")
public class ClassPojo {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@TableField(value = "class_name")
private String className;
}
添加Mapper文件
@Mapper
public interface ClassMapper extends BaseMapper<ClassPojo> {
}
添加Service介面
public interface ClassVoService extends IService<ClassPojo> {
String getClassName(Long id);//自定義方法
}
添加Service實現類
@Component
public class ClassVoServiceImpl extends ServiceImpl<ClassMapper, ClassPojo> implements ClassVoService {
public String getClassName(Long id){
ClassPojo byId = getById (id);
return byId.getClassName ();
}
}
添加Controller
@RestController
@RequestMapping("/demo")
public class ExcelController {
@GetMapping("/getbyid")
public String getbyid(){
return classVoService.getClassName (1l);
}
}
補充對應表結構
CREATE TABLE `class_table` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '課程id不能為空主鍵',
`class_name` varchar(255) NOT NULL COMMENT '課程名稱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
表數據如下
id | class_name |
---|---|
1 | 語文 |
2 | 數學 |