10 myBatis-02

註解方式使用MyBatis,在一些單表操作或者業務邏輯簡單的系統應用中可以採用基於註解方式類完成CRUD操作。

和09 myBatis-01的代碼基本類似,主要少了Mapper文件,myBais主配置文件內有差異,接口來內部包含註解

0、項目文件結構

1、pom.xml配置

同09 myBatis-01

2、Mybatis主配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://47.100.229.xxx:3306/springStudy?useSSL=false&serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="xxxx"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 引入表的接口類 -->
    <mappers>
        <mapper class="db.Dao.EmployeeDao"  />
    </mappers>
</configuration>

3、單個表對應的內容

3.1、模型類

同09 myBatis-01

3.2、數據接口類

每個方法上邊通過註解指定相關的Sql語句

package db.Dao;

import db.Domain.Employee;
import org.apache.ibatis.annotations.*;

import java.util.List;

//數據訪問接口 - 註解方式
public interface EmployeeDao {

    //查詢單個對象,單個參數時@Param可以省略
    @Select(" select * from Employee where emplId=#{emplId} ")
    public Employee queryByEmplId(@Param("emplId") String empId);

    //查詢多個對象,多個參數時需要通過@Param聲明
    @Select(" select * from Employee where salary BETWEEN #{start} and #{end} ")
    public List<Employee> queryListBySalary(@Param("start") int start, @Param("end") int end);

    //新增數據
    @Insert(" insert into employee(emplId,`name`,gender,hireDate,salary) values(#{emplId},#{name},#{gender},#{hireDate},#{salary}) ")
    public int insert(Employee emp);

    //更新數據
    @Update(" update employee set `name`=#{name},gender=#{gender},salary=#{salary} where emplId=#{emplId} ")
    public int update(Employee emp);

    //刪除數據
    @Delete(" delete from employee where emplId=#{emplId} ")
    public void delete(@Param("emplId") String empId);

}

3.3、Mapper文件

無需提供

3.4、主配置文件引用Mapper文件

通過Class引用接口類

3.5、測試代碼

同09 myBatis-01 

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