1. 程式人生 > >一個簡單的MyBatis完成插入操作的例子(二)

一個簡單的MyBatis完成插入操作的例子(二)

配置好mybatis-config.xml檔案後,我們在com.sk.pojo下建立一個pojo類,類名為Student
Student類需要與資料庫中的欄位一一對映

public student(){
    private Integer id;
    private String name;
    private String age;
    private String phone;
    public Student() {
    }
    public Student(Integer id, String name, String age, String phone) {
        super();
        this
.id = id; this.name = name; this.age = age; this.phone = phone; } get&set...... public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + ", phone=" + phone + "]"; } }

可以利用Shift+Alt+S快速構造一個無參構造器、全參構造器、get&set方法、toString方法。
注意:無參構造器必須要有,不然會報錯。

student類建立完成後,需要在com.sk.mapper下建立一個介面StudentMapper(相當於Dao層)

package com.sk.mapper;

import com.sk.pojo.Student;

public interface StudentMapper {
    public void insertStudent(Student student); 
}

建立完介面後,要在mybatis-config.xml中配置該介面的對映
在mybatis-config.xml的mappers標籤內加入如下內容:

<mappers>
<mapper resource="com/sk/mapper/StudentMapper.xml" /> </mappers>

注意:
1.可以在介面中選中介面名右擊,選擇Copy Qualified Name,複製介面的路徑,貼上到“resource=“後面
2.貼上完成後按住ctrl點選路徑,如果能正確跳轉到介面,則為正確路徑

介面建立完成後,在com.sk.mapper下建立一個StudentMapper.xml檔案

<?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.sk.mapper.StudentMapper">
    <resultMap type="student" id="StudentMapperResult">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="age" column="age" />
        <result property="phone" column="phone" />
    </resultMap>
    <insert id="insertStudent" parameterType="student"> 
        INSERT INTO
        STUDENT(ID,NAME,AGE,PHONE,TEA_ID) 
        VALUES(#{id},#{name},#{age},#{phone}) 
    </insert>
</mapper>
<mapper namespace="com.sk.mapper.StudentMapper">

是我們定義介面的全限定名字,這樣就可以使用介面呼叫對映的SQL語句了,這個名字一定要和介面對應。

<resultMap type="student" id="StudentMapperResult">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="age" column="age" />
        <result property="phone" column="phone" />
</resultMap>

resultMap為對映結果集。resultMap的id值應該在此名空間內是唯一的,並且type屬性是完全限定類名或者是返回型別的別名。result子元素被用來將一個resultset列對映到物件的一個屬性中。
id元素和result元素功能相同,不過id被用來對映到唯一標識屬性,用來區分和比較物件(一般和主鍵列相對應)。

<insert id="insertStudent" parameterType="student"> 
        INSERT INTO
        STUDENT(ID,NAME,AGE,PHONE) 
        VALUES(#{id},#{name},#{age},#{phone}) 
</insert>

在insert語句中配置了resutlMap屬性,MyBatis會使用表中的列名與物件屬性對映關係來填充物件中的屬性值。
id屬性對映到一個insertStudent()方法,該方法便是StudentMapper介面中的insertStudent()方法,parameterType元素為該方法傳入的引數型別Student。
insert元素內的語句為sql語句,#{}相當於一個佔位符,通過實現insertStudent方法將引數傳入。