溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

MyBatis參數(shù)處理及測試增刪改查

發(fā)布時間:2020-04-27 05:32:34 來源:網(wǎng)絡(luò) 閱讀:1212 作者:Adam的blog 欄目:開發(fā)技術(shù)

POJO

private Integer id;
    private String lastName;
    private String email;
    private String gender;
    //getter and setter

接口

public interface EmployeeMapper {

    //查詢
    public Employee getEmployeeById(Integer id);

    //多條件查詢
    public Employee getEmpLoyeeByIdAndName(@Param("id") Integer id, @Param("lastName") String lastName);

    //添加
    public void addEmp(Employee employee);

    //修改
    public void updateEmp(Employee employee);

    //刪除
    public void deleteEmpById(Integer id);
}

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="test">
            <transactionManager type=""></transactionManager>
            <dataSource type=""></dataSource>
        </environment>

        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url"
                    value="jdbc:mysql://localhost:3306/mybatis?useSSL=false" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>

    <!-- 將我們寫好的sql映射文件(testEmployeeMapper.xml)注冊到全局配置文件(mybatis-config.xml)中 -->
    <mappers>
        <mapper resource="testEmployeeMapper.xml" />
    </mappers>
</configuration>

測試類

public class MyBatisTest {

    // 獲取SqlSessionFactory對象
    private SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);

        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    /**
     * 測試增刪改
     *  1. 需要手動提交數(shù)據(jù)
     *      sqlSessionFactory.openSession();        ===》 手動提交
     *      sqlSessionFactory.openSession(true);    ===》 自動提交
     *  2. 可以有返回值,返回值類型是一下幾種:
     *      Long, Integer,Boolean,void
     * @throws IOException
     */
    @Test
    public void test03() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //獲取到的SqlSession對象不會自動提交數(shù)據(jù)
        SqlSession openSession = sqlSessionFactory.openSession();

        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);

            //測試單個參數(shù)查詢
//          Employee employee = mapper.getEmployeeById(2);
//          System.out.println(employee);

            //測試多個參數(shù)查詢
            Employee employee = mapper.getEmpLoyeeByIdAndName(2, "xiaobai");
            System.out.println(employee);

            //添加一條數(shù)據(jù)
//          Employee employee = new Employee(null, "xiaobai", "xiaobai@zgz.com", "0");
//          mapper.addEmp(employee);
//          System.out.println(employee.getId());

            //更新數(shù)據(jù)
//          Employee employee = new Employee(1, "xiaobai", "xiaobai@zgz.com", "0");
//          mapper.updateEmp(employee);

            //刪除數(shù)據(jù)
//          mapper.deleteEmpById(1);

            //手動提交數(shù)據(jù)
//          openSession.commit();
        } finally {
            openSession.close();
        }

    }
}

Sql映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zgz.MyBatis.dao.EmployeeMapper">
<!--
    namespace: 名稱空間
    id: 唯一標識
    resultType: 返回值類型 
    #{id}: 從傳遞過來的參數(shù)中取出id值

    在MyBatis中,接口可以與配置文件實現(xiàn)動態(tài)綁定,綁定方式:
        1. 把namespace指定為接口的全類名
        2. 把id換成接口中的方法,可以把select標簽和接口中的方法進行綁定
 -->

    <!-- 
        使用#{}取值和${}取值的區(qū)別:
            #{}:是以預(yù)編譯的形式,將參數(shù)設(shè)置到sql語句中,防止sql注入,一般均使用#{}
            ${}:取出的值直接拼裝在sql語句中,會有安全問題,對于不支持預(yù)編譯(不支持占位符)的原生jdbc,可以使用${},比如${tableName};
            eg:
                select * from test where id = #{id} and name = ${name};
                select * from test where id = ? and name = xiaoming;
     -->

    <!--
        參數(shù)傳遞:
            單個參數(shù):mybatis不會做特殊處理
                用#{參數(shù)名}的形式去除參數(shù)值,參數(shù)名可以隨便起,但最好要直觀
            多個參數(shù):mybatis會對其進行特殊處理
                多個參數(shù)會被封裝成一個map
                    key:param1...paramN
                    value:傳入的參數(shù)值
                #{}就是從map中取出參數(shù)值,用 #{param1}或#{0}取出第一個值,以此類推取出n個值
            命名參數(shù):#{param1},可讀性不好,采用注解的形式增加可讀性
                public Employee getEmpLoyeeByIdAndName(@Param("id") Integer id, @Param("lastName") String lastName);
            傳遞多個參數(shù):
                1. POJO:
                    如果參數(shù)正好是業(yè)務(wù)邏輯的數(shù)據(jù)模型,可以直接傳入pojo;#{屬性名}:取出傳入的pojo的屬性值
                2. Map:
                    如果多個參數(shù)不是業(yè)務(wù)邏輯的數(shù)據(jù)模型,沒有對應(yīng)的pojo,為了方便可以傳入map;#{key}:取出map中的值
                    Collection類型:key為collection
                    List類型:key為list
                    數(shù)組類型:key為array
                3. TO:
                    如果多個參數(shù)不是業(yè)務(wù)模型中的數(shù)據(jù),但是經(jīng)常使用,可以編寫一個TO(Transfer Object)數(shù)據(jù)傳輸對象
                    例如:做分頁的時候可以傳入一個
                        Page{
                            int index;
                            int size;
                        }
    -->
    <!-- 單個參數(shù)查詢 -->
    <select id="getEmployeeById" resultType="com.zgz.MyBatis.bean.Employee">
        select id,last_name lastName,email,gender from tbl_employee where id = #{id}
    </select>
    <!-- 多個參數(shù)查詢 -->
    <select id="getEmpLoyeeByIdAndName" resultType="com.zgz.MyBatis.bean.Employee">
        select id, last_name lastName, email, gender 
        from tbl_employee 
        where id = #{id} and last_name = #{lastName}
    </select>

    <!-- 
        MyBatis獲取自增主鍵:
            1. useGeneratedKeys="true",使用主鍵自增策略
            2. keyProperty="id",指定對應(yīng)主鍵屬性,也就是mybatis獲取到主鍵后將這個值封裝給javaBean的哪個屬性
        Oracle不支持主鍵自增:Oracle使用序列來模擬自增
        每次插入的數(shù)據(jù)的主鍵是從序列中拿到的值,如何獲取到這個值
     -->
     <!-- 增刪改時返回的是影響的行數(shù) --> 
    <insert id="addEmp" parameterType="com.zgz.MyBatis.bean.Employee"
        useGeneratedKeys="true" keyProperty="id">
        insert into tbl_employee(last_name, email, gender) 
            values(#{lastName},#{email},#{gender})
    </insert>

    <update id="updateEmp" parameterType="com.zgz.MyBatis.bean.Employee">
        update tbl_employee
            set  last_name=#{lastName},email=#{email},gender=#{gender}
            where id = #{id}
    </update>

    <delete id="deleteEmpById" parameterType="com.zgz.MyBatis.bean.Employee">
        delete from tbl_employee where id = #{id} 
    </delete>
</mapper>
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI