Spring Boot 2.x快速上手(九)Spring Boot與MyBatis整合

MyBatis 是一款優秀的持久層框架,它支持定製化 SQL、存儲過程以及高級映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動設置參數以及獲取結果集。MyBatis 可以使用簡單的 XML 或註解來配置和映射原生信息,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對象)映射成數據庫中的記錄。


目錄

一、Spring Boot與MyBatis整合

二、MyBatis數據查詢

三、創建數據

四、更新與刪除數據

五、小結


一、Spring Boot與MyBatis整合

首先,創建一個新的項目,模板還是選擇web和mysql,這裏不選擇mybatis,因爲mybatis的starter不是由springframewor提供的,pom文件中的引用很顯然和其他的包是由很大的區別的:

完成創建之後,我們需要在application.properties文件中進行數據源,mybatis的相關配置,當然了,配置文件中相應的包和文件都要進行創建:

#Datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/scoot?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

#mybatis
#Core Config File
#Start width /
mybatis.config-location=classpath:/mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:/mybatis/mapper/*.xml

 接下來進行相關實體類、業務邏輯、實現類、控制類的編寫:

實體類:

@Getter
@Setter
//@AllArgsConstructor
public class Emp {
    private Integer empno;
    private String ename;
    private String job;
    private Integer mgr;
    private Date hiredate;
    private Float sal;
    private Float comm;
    private Integer deptno;
}

 業務邏輯接口:

public interface EmpMapper {

    public Emp findById(Integer empno);
}

實現類:

@Service
public class EmpService {
    @Resource
    private EmpMapper empMapper =null;

    public Emp findById(Integer empno){
        Emp emp = empMapper.findById(empno);
        return  emp;
    }
}

 控制類:

@RestController
public class EmpController {
    @Resource
    private EmpService empService = null;

    @RequestMapping("/emp/{id}")
    public Emp  findById(@PathVariable("id") Integer id){
        Emp emp = empService.findById(id);
        return emp;
    }
}

 最後進行實體類Emp類查詢的mapper映射文件配置:

<!--映射文件配置,namespace指向接口-->
<mapper namespace="com.laoqi.springbootmybatis.mapper.EmpMapper">
    <select id="findById" parameterType="Integer"  resultType="com.laoqi.springbootmybatis.entity.Emp">
        select * from emp where empno = #{value}
    </select>
</mapper>

 在入口類中添加包的掃描,然後啓動測試即可:

@MapperScan("com.laoqi.springbootmybatis.mapper")

 測試結果:

二、MyBatis數據查詢

下面以具體的一個查詢數據案例舉例說明,編寫一個具體的案例查詢語句:

select * from emp e ,dept d where e.deptno = d.deptno and d.dname="RESEARCH"  and  e.sal >1500

還是按照業務邏輯接口、實現類、控制類進行編寫代碼,

業務邏輯接口:

public List<Map> findDepts(Map param);

實現類:

public List<Map> findDepts(String dname, Float sal) {
    Map param = new HashMap();
    param.put("pdname", dname);
    param.put("psal", sal);
    return empMapper.findDepts(param);
}

 控制類:

    @RequestMapping("/emp/list")
    public List<Map> findDepts(String dname,Float sal){
        List<Map> list =  empService.findDepts(dname,sal);
        return list;
    }

 最後進行mapper映射文件的配置,這裏使用if語句進行條件的選擇查詢:

<!--  resultType 代表將查詢到的每一條記錄都包裝爲map,key值是字段名,value是字段值  -->
    <select id="findDepts"  parameterType="java.util.Map" resultType="java.util.LinkedHashMap">
        select * from emp e ,dept d where e.deptno = d.deptno
        <if test="pdname!=null" >
            and dname=#{pdname}
        </if>
        <if test="psal!=null">
            and  sal >#{psal}
        </if>
    </select>

 測試結果:

三、創建數據

創建數據依舊按照舉例的方式進行學習,

INSERT INTO `scoot`.`emp`(`empno`, `ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`) VALUES (7900, 'JAMES', 'CLERK', 7698, '1981-12-03', 950.00, NULL, 30);

還是按照業務邏輯接口、實現類、控制類進行編寫代碼,

業務邏輯接口:

public void create(Emp emp);

實現類:

    @Transactional(rollbackFor = Exception.class)
    public void create(Emp emp){
        empMapper.create(emp);
    }

控制類:

    @RequestMapping("/emp/create")
    public Emp create(){
        Emp emp = new Emp();
        emp.setSal(1000f);
        emp.setComm(0f);
        emp.setDeptno(30);
        emp.setEname("laoqi");
        emp.setHiredate(new Date());
        emp.setJob("teacher");
        emp.setMgr(null);
        empService.create(emp);
        return  emp;
    }

  最後進行mapper映射文件的配置,

<insert id="create" parameterType="com.laoqi.springbootmybatis.entity.Emp">
        INSERT INTO `scoot`.`emp`(`ename`, `job`, `mgr`, `hiredate`, `sal`, `comm`, `deptno`)
        VALUES (#{ename}, #{job}, #{mgr}, #{hiredate}, #{sal}, #{comm}, #{deptno})
        <!-- 自動進行主鍵回填 select LAST_INSERT_ID()用於獲取最新插入的id,是mysql內置函數-->
        <selectKey keyProperty="empno" keyColumn="empno" resultType="Integer" order="AFTER">
            select LAST_INSERT_ID()
        </selectKey>
    </insert>

 測試結果:

四、更新與刪除數據

數據的更新與刪除,依舊是按照代碼編寫順序就行編寫就OK了,在這裏不進行重複的代碼粘貼了。

五、小結

SB整合mybatis還是採用添加依賴,進行簡單的數據源和mybatis的相關配置即可進行使用,熟悉了對插件工具的使用,和了解這些東西的作用,提高開發效率就已經達到目的了。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章