【持久化框架MyBatis3三】MyBatis3 SQL映射配置文件

 SQL映射配置文件一方面类似于Hibernate的映射配置文件,通过定义实体与关系表的列之间的对应关系。另一方面使用<select>,<insert>,<delete>,<update>元素定义增删改查的SQL语句,

这些元素包含三方面内容

1. 要执行的SQL语句

2. SQL语句的入参,比如查询条件

3. SQL语句的返回结果,包括查询结果,更新结果等等

基本的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.mybatis3.mappers.StudentMapper">

    <!--resultMap定义了SQL列与type指定的POJO类的属性之间的映射关系-->
    <!--type属性表示要转换的ORM的POJO-->
    <!--id属性用来指示resultMap这个配置,在配置的其它地方可以引用-->
    <resultMap type="Student" id="StudentResult">
		<id 	property="studId" column="stud_id"/>
		<result property="name" column="name"/>
		<result property="email" column="email"/>
		<result property="dob" column="dob"/>
	</resultMap>

    <!--resultMap属性指的是一行转换规则-->
    <!--这个语句根据需要可以返回List或者唯一的一行数据-->
  	<select id="findAllStudents" resultMap="StudentResult">
    	select * from Students
  	</select>

    <!--如果SQL查询返回多行数据,这个查询可以请求MyBatis返回一个List<Student>-->
  	<select id="findStudentById" parameterType="int" resultType="Student">
        <!--如果查询的列名称与POJO的属性名不一致,使用SQLas语法-->
    	select stud_id as studId, name, email, dob from Students where stud_id=#{studId}
  	</select>

    <!--如何返回插入语句的主键-->
  	<insert id="insertStudent" parameterType="Student">
  		INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})
  	</insert>
  	
  	<update id="updateStudent" parameterType="Student">
  		UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}
  	</update>
  	
</mapper>

resultMap元素

resultMap元素是MyBatis对查询结果进行ORM的主要配置项,简单的说它类似于Hibernate的实体与POJO的映射配置,resultMap的属性和子配置项包括:

resultMap元素的属性

  • id:定义resultMap配置项的唯一ID,用于标示resultMap,在<select>中可以引用
  • type: 定义要映射的实体类型,可以使用类型别名
  • extends:用于具有继承关系的resultMap的定义,比如实体B继承自实体A,那么定义B的resultMap时,可以让它继承自A对应的resultMap
  • autoMapping:true|false 含义用法未知

SQL表列名与POJO字段之间的映射关系

  	<select id="findStudentById" parameterType="int" resultType="Student">
            select stud_id, name, email, dob from Students where stud_id=#{studId}
  	</select>
  • 当列名与POJO属性名一样时,MyBatis自动将列的取值设置到POJO字段上,比如
  • 当列名与POJO属性名不一样时,MyBatis不会将列的取值设置到POJO字段上,所以上面的例子中返回的Student对象,studId字段为null
  • 可以使用SQL的列名的as语法,将列名重命名为对应的POJO的属性名如 select stud_id as studId
  • 大多数的列名和POJO的字段名通常是不一致的,而且我们会写多个<select>查询语句,如果都是用列名as语法进行重命名,那么将会很繁琐,MyBatis提供了一种列名和属性名映射关系,称之为ResultMap,这里的Map是Mapping,即结果的映射,而不是指result是一个Map,ResultMap的真实含义类似于Hibernate的Table与POJO之间的映射关系
    <!--resultMap定义了SQL列与type指定的POJO类的属性之间的对象关系-->  
    <!--type属性表示要转换的ORM的POJO-->  
    <!--resultMap的id属性用来指示resultMap这个配置,在配置的其它地方可以引用-->  
    <resultMap type="Student" id="StudentResult">  
        <!--The <id> element is similar to <result> but is used to map the identifier property  that is used for comparing objects.-->
        <id  property="studId" column="stud_id"/>  
        <result property="name" column="name"/>  
        <result property="email" column="email"/>  
        <result property="dob" column="dob"/>  
    </resultMap>  
  
    <!--resultMap属性指的是一行转换规则-->  
    <!--这个语句根据需要可以返回List或者唯一的一行数据-->  
    <select id="findAllStudents" resultMap="StudentResult">  
        select * from Students  
    </select> 

 resultMap和resultType

  •  在一个select配置项中,select可以包含resultMap或者resultType,用于指定返回的类型,但是二者不能同时出现
  • resultMap和resultType的含义是select结果集的一行进行映射,不是说整个SQL的查询结果的类型是resultMap或者resultType类型
  • sqlSession.selectOne("<select>.id")表示之返回一行数据,sqlSession.selectList表示返回多行数据

主键自动增长的方式插入数据

<insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="studId">
    INSERT INTO STUDENTS(NAME, EMAIL, PHONE)VALUES(#{name},#{email},#{phone})
</insert>
  • useGeneratedKeys为true表示插入数据时使用MySQL自动生成主键,
  • keyProperty表示这个主键值存储在哪个属性中

 上面这个insert操作,传入的参数是Student类型,由于没有持久化,所以Student的studId属性是null,执行完insert语句后,作为传入参数的Student对象的studId包含了数据库自动生成的主键ID

API执行增删改查的方式

还有第三种,注解的方式,注解这种方式,实际工作中基本不会用

Mapper方式

1.定义接口StudentMapper,与配置文件中mapper的namespace一致

<mapper namespace="com.mybatis3.mappers.StudentMapper">

2.定义StudentMapper接口

StudentMapper接口的方法签名与配置文件中的<select>,<insert>,<update>,<delete>保持一致,方法名id属性,参数类型parameterType,返回结果类型resultType或者resultMap

package com.mybatis3.mappers;

import java.util.List;

import com.mybatis3.domain.Student;


public interface StudentMapper {

    List<Student> findAllStudents();

    Student findStudentById(Integer id);

    void insertStudent(Student student);

    void updateStudent(Student student);

    List<Student> findStudentById2();

}

注意:

  • Mapper的权限定类名跟mapper的namespace属性保持一致
  • 方法签名与配置文件中的<select>,<insert>,<update>,<delete>保持一致,方法名id属性,参数类型parameterType,返回结果类型resultType
  • StudentMapper的用法
	public List<Student> findAllStudents() {
        SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); //SqlSession定义了获取Mapper的方法
            return studentMapper.findAllStudents();
        } finally {
            sqlSession.close();
        }
    }

SQL映射的方式

Student student = (Student)sqlSession.selectOne("com.mybatis3.mappers.StudentMapper.findStudentById",studId);

SqlSession的方法selectXXX,updateXXX,deleteXXX和insertXXX遵循这种方式,第一个参数是配置文件里namespace + id取得一个SQL操作,第二个参数是SQL语句的参数,由parameterType限定

猜你喜欢

转载自bit1129.iteye.com/blog/2113461