一个简单的MyBatis完成插入操作的例子(二)

来源:互联网 发布:软件编程教学 编辑:程序博客网 时间:2024/06/08 00:37

配置好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方法将参数传入。

0 0
原创粉丝点击