1. 程式人生 > >MyBatis參數處理及測試增刪改查

MyBatis參數處理及測試增刪改查

arr 增加 oracle delet fig uil input collect cti

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. 需要手動提交數據
     *      sqlSessionFactory.openSession();        ===》 手動提交
     *      sqlSessionFactory.openSession(true);    ===》 自動提交
     *  2. 可以有返回值,返回值類型是一下幾種:
     *      Long, Integer,Boolean,void
     * @throws IOException
     */
    @Test
    public void test03() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        //獲取到的SqlSession對象不會自動提交數據
        SqlSession openSession = sqlSessionFactory.openSession();

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

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

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

            //添加一條數據
//          Employee employee = new Employee(null, "xiaobai", "[email protected]", "0");
//          mapper.addEmp(employee);
//          System.out.println(employee.getId());

            //更新數據
//          Employee employee = new Employee(1, "xiaobai", "[email protected]", "0");
//          mapper.updateEmp(employee);

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

            //手動提交數據
//          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}: 從傳遞過來的參數中取出id值

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

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

    <!--
        參數傳遞:
            單個參數:mybatis不會做特殊處理
                用#{參數名}的形式去除參數值,參數名可以隨便起,但最好要直觀
            多個參數:mybatis會對其進行特殊處理
                多個參數會被封裝成一個map
                    key:param1...paramN
                    value:傳入的參數值
                #{}就是從map中取出參數值,用 #{param1}或#{0}取出第一個值,以此類推取出n個值
            命名參數:#{param1},可讀性不好,采用註解的形式增加可讀性
                public Employee getEmpLoyeeByIdAndName(@Param("id") Integer id, @Param("lastName") String lastName);
            傳遞多個參數:
                1. POJO:
                    如果參數正好是業務邏輯的數據模型,可以直接傳入pojo;#{屬性名}:取出傳入的pojo的屬性值
                2. Map:
                    如果多個參數不是業務邏輯的數據模型,沒有對應的pojo,為了方便可以傳入map;#{key}:取出map中的值
                    Collection類型:key為collection
                    List類型:key為list
                    數組類型:key為array
                3. TO:
                    如果多個參數不是業務模型中的數據,但是經常使用,可以編寫一個TO(Transfer Object)數據傳輸對象
                    例如:做分頁的時候可以傳入一個
                        Page{
                            int index;
                            int size;
                        }
    -->
    <!-- 單個參數查詢 -->
    <select id="getEmployeeById" resultType="com.zgz.MyBatis.bean.Employee">
        select id,last_name lastName,email,gender from tbl_employee where id = #{id}
    </select>
    <!-- 多個參數查詢 -->
    <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",指定對應主鍵屬性,也就是mybatis獲取到主鍵後將這個值封裝給javaBean的哪個屬性
        Oracle不支持主鍵自增:Oracle使用序列來模擬自增
        每次插入的數據的主鍵是從序列中拿到的值,如何獲取到這個值
     -->
     <!-- 增刪改時返回的是影響的行數 --> 
    <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>

MyBatis參數處理及測試增刪改查