mybatis學習 (四) 瞭解映射器的配置

映射器是javaBean和數據庫表溝通的橋樑, 必須掌握它的使用
它的內容如下表

這裏寫圖片描述
這裏寫圖片描述

select


這是最簡單的用法了, 根據id來返回一個實體。

        <select id="getStudent" parameterType="integer" resultType="student">
            select * from student where stuId = #{stuId}
        </select>

參數解釋
id 和接口中的方法定義一致
parameterType 要傳給sql的參數類型, 可以是全路徑或別名
resultType 結果類型,可以是全路徑或別名

統計姓王的學生人數, 步驟如下

1 . 在接口中定義方法

public Student countFirstName(String name);

2 . 配置select標籤
這裏需要注意的是like的 %寫法

<select id="countFirstName" parameterType="string" resultType="integer">
            select count(*) FROM student where stuName like concat(#{firstName} ,'%')
        </select>

3 . 測試

    @Test
    public void test() throws IOException {
        SqlSession sqlSession = null;
        try {
           sqlSession = SqlSessionFactoryUtil.openSqlSession();
           StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            System.out.println(studentMapper.countFirstName("王"));
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sqlSession != null){
                sqlSession.close();
            }
        }
    }
select的自動映射

假如有一個這樣的字段,在數據庫中是stu_id, 用下劃線分割了兩個詞, 但是javabean中的命名爲stuId, 兩種不能互相對應。
解決辦法是 ,用as將放回列表重命名成javabean的屬性

 <select id="getStudent" parameterType="integer" resultType="student">
            SELECT stu_id AS stuId , stu_name AS stuName,stu_age AS stuAge,stu_major AS stuMajor,birthday  FROM student WHERE stu_Id = #{stuId}
        </select>
多個值傳遞

上面傳遞一個值還是挺簡單的, 當有多個值的時候 用map將列名對應的參數傳入.
比如查找姓氏爲王, 年齡18的學生
接口方法

 public List<Student> findByNameAndAge(Map<String, String> params);

xml

    <select id="findByNameAndAge" parameterType="map" resultType="student">
       SELECT stu_id AS stuId , stu_name AS stuName,stu_age AS stuAge,stu_major AS stuMajor,birthday
        FROM student WHERE stu_name LIKE concat(#{name},'%') AND stu_age = #{age};
    </select>

測試

 @Test
    public void test() throws IOException {
        SqlSession sqlSession = null;
        try {
           sqlSession = SqlSessionFactoryUtil.openSqlSession();
           StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
           Map<String, String> paramsMap = new HashMap<String, String>();
           paramsMap.put("name","王");
           paramsMap.put("age","18");
           System.out.println(studentMapper.findByNameAndAge(paramsMap));
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sqlSession != null){
                sqlSession.close();
            }
        }
    }
多值傳遞 –註解方式

在接口方法參數上加上@Param(“name”) 也可以將值傳入

public List<Student> findByNameAndAge(@Param("name") String name, @Param("age") Integer age);

xml, 不需要指定parameterType

 <select id="findByNameAndAge"  resultType="student">
       SELECT stu_id AS stuId , stu_name AS stuName,stu_age AS stuAge,stu_major AS stuMajor,birthday
        FROM student WHERE stu_name LIKE concat(#{name},'%') AND stu_age = #{age};
    </select>

測試代碼

studentMapper.findByNameAndAge("王",18)
使用javabean 方式傳入

需要針對查詢的參數來重新創建一個類,類的屬性就是查詢的參數,如下

public class StuParam {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

接口創建以這個參數類爲參數的方法

public List<Student> findByNameAndAge(StuParam stuParam);

xml, 指定輸入類型爲StuParam類


    <select id="findByNameAndAge"  parameterType="com.cyh.pojo.StuParam" resultType="student">
       SELECT stu_id AS stuId , stu_name AS stuName,stu_age AS stuAge,stu_major AS stuMajor,birthday
        FROM student WHERE stu_name LIKE concat(#{name},'%') AND stu_age = #{age};
    </select>

測試:

studentMapper.findByNameAndAge(new StuParam("王",18));

3種多值傳遞方法感覺還是註解的方便一些。

insert


插入的規則要比查詢簡單很多, 只要注意普通的查詢是不返回主鍵的,如下代碼

 @Test
    public void test() throws IOException {
        SqlSession sqlSession = null;
        try {
           sqlSession = SqlSessionFactoryUtil.openSqlSession();
           StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

           Student stu = new Student();
           stu.setStuName("劉si");
           stu.setStuAge(12);
           stu.setStuMajor("軟件");
           stu.setBirthday(new Date());

            studentMapper.insertStudent(stu);
            sqlSession.commit();

            System.out.println(stu.getStuId());
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sqlSession != null){
                sqlSession.close();
            }
        }
    }

輸出的id是null, 主鍵不回填, 後面若是需要對stu這個對象操作的話就麻煩了, 在xml中有解決的辦法,如下 . 設置useGeneratedKeys爲true , keyProperty爲pojo的主鍵屬性

 <insert id="insertStudent" parameterType="student"
            useGeneratedKeys="true" keyProperty="stuId">
            insert into student(stu_name, stu_age, stu_major, birthday) values(#{stuName},#{stuAge},#{stuMajor},#{birthday})
        </insert>

update

參數傳遞的方式和select 一樣
接口如下

public Integer updateStudent(Student stu);

xml 如下

    <update id="updateStudent" parameterType="student"  >
        UPDATE student SET stu_name=#{stuName} WHERE stu_id = #{stuId}
    </update>

測試

@Test
    public void test() throws IOException {
        SqlSession sqlSession = null;
        try {
           sqlSession = SqlSessionFactoryUtil.openSqlSession();
           StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

           Student stu = new Student();
           stu.setStuId(6);
           stu.setStuName("新名字哎");
           studentMapper.updateStudent(stu);
            sqlSession.commit();
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            if (sqlSession != null){
                sqlSession.close();
            }
        }
    }

注意一點是, 這裏只按id修改了學生的姓名,沒有傳入stuMajor參數, 但是數據庫不會將stu_major字段設置爲null, 而是保留上一次的內容

delete

     <delete id="deleteStudent" parameterType="integer">
         delete FROM student WHERE stu_id = #{stuid}
     </delete>
發佈了684 篇原創文章 · 獲贊 241 · 訪問量 72萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章