SpringBoot整合Mybatis【註解版】
阿新 • • 發佈:2018-12-31
一、專案建立
- 新建一個工程
- 選擇Spring Initializr,配置JDK版本
- 輸入專案名
- 選擇構建web專案所需的staters(啟動器)
- 選擇與資料庫相關的元件
分析:Spring Boot基本上將我們實際專案開發中所遇到的所有場景都做了封裝。它將所有的功能場景都抽取出來,做成了一個個的staters(啟動器),只需要在專案的pom.xml配置檔案裡面引入這些starter相關場景的所有依賴都會匯入進來。需要什麼功能就匯入什麼場景的啟動器,實質就是通過配置匯入了與實現其功能相關的jar包,然後直接進行項開發即可。
- 選擇儲存地址後點擊Finish
- 注意:idea必須在聯網環境下才會自動構建專案
- 在專案中使用druid作為資料來源,不會的請點選SpringBoot整合Druid資料來源
- 在bean包下新建實體類物件Department (職位)
package com.cyn.bean; /** * @author:cyn * @create:2018/12/30 16:17 * @description:職位實體類 */ public class Department { private Integer id; //職位id private String departmentName; //職位名 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getDepartmentName() { return departmentName; } public void setDepartmentName(String departmentName) { this.departmentName = departmentName; } }
- 新建資料庫mybatis,在資料庫中新建與實體類物件相關聯的資料庫表 department
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for department -- ---------------------------- DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_INCREMENT, `departmentName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
- 在mapper包下新建與實體類所關聯的mapper介面【註解版】:DepartmentMapper
package com.cyn.mapper;
import com.cyn.bean.Department;
import org.apache.ibatis.annotations.*;
/**
* @author:cyn
* @create:2018/12/30 16:19
* @description:職位實體類mapper介面
*/
//指定這是一個操作資料庫的mapper
@Mapper
public interface DepartmentMapper {
@Select("select * from department where id = #{id}")
public Department getDeptById(Integer id);
@Delete("delete from department where id = #{id}")
public int deleteDeptById(Integer id);
//指定表的id列為自增主鍵並自動繫結到pojo
@Options(useGeneratedKeys = true,keyColumn = "id")
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDept(Department department);
@Update("update department set departmentName = #{departmentName} where id = #{id}")
public int updateDept(Department department);
}
-
常用註解總結:
- @Mapper:將mapper介面註冊到容器中
- @Select:查詢
- @Delete:刪除
- @Insert:插入
- @Update:更新
- @Options(useGeneratedKeys = true,keyColumn = "id"):指定表的自增主鍵並自動繫結到實體類物件
- @Result 修飾返回的結果集,關聯實體類屬性和資料庫欄位一一對應,如果實體類屬性和資料庫屬性名保持一致, 就不需要這個屬性來修飾。
- 在controller包下新建controller控制類:DeptController
package com.cyn.controller;
import com.cyn.bean.Department;
import com.cyn.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* @author:cyn
* @create:2018/12/30 16:27
* @description:職位管理
*/
@RestController
public class DeptController {
@Autowired
DepartmentMapper departmentMapper;
@GetMapping("/dept/{id}")
public Department getDepartment(@PathVariable("id") Integer id){
return departmentMapper.getDeptById(id);
}
@GetMapping("dept")
public Department insertDeptment(Department department){
departmentMapper.insertDept(department);
return department;
}
}
- @RestController:等價於同時使用@ResponseBody和@Controller
- @GetMapping("/dept/{id}"):等價於@RequestMapping(value = "/dept/{id}",method = RequestMethod.GET)
- /dept/{id}:controller中的url採用restful形式,不會的請自行百度
- @PathVariable("id"):將url中相對應引數名的值繫結到指定的形參上
- 最後專案結構目錄如下
二、其他配置分析
- 如果資料庫表滿足駝峰命名規則,查詢時候資料則無法自動對映到相對應的實體類屬性上,我們可以在config包下新建一個自動配置類:MybatisConfig
package com.cyn.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
/**
* @author:cyn
* @create:2018/12/30 17:04
* @description:自定義Mybatis的配置規則
*/
@org.springframework.context.annotation.Configuration
public class MybatisConfig {
//註冊到容器中
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(Configuration configuration) {
//開啟駝峰命名規則
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
- 如果我們不想每次都在mapper介面上新增@Mapper註解,我們可以在主配置類上通過新增@MapperScan註解來批量掃描指定包下的所有mapper介面,如下:
package com.cyn;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//新增對mapper的自動掃描
@MapperScan(value = "com.cyn.mapper")
@SpringBootApplication
public class SprignbootDataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SprignbootDataMybatisApplication.class, args);
}
}
三、專案測試:
- 啟動專案,在url位址列輸入插入操作:http://localhost:8080/dept?departmentName=AAA
- 觀察資料庫,看是否插入成功
- 再在url位址列輸入查詢操作:http://localhost:8080/dept/1
- 至此,springboot整合mybatis成功!如果你失敗了,繼續除錯吧騷年!