前言:
我们知道,每一款框架产品在实际开发中,都是通过XML文件来培训框架的相关流程的,MyBatis也不例外,主要有两个配置文件:config.xml和Mapper.xml,当然,这两种配置文件可以自定义文件名。
config.xml是全局配置文件,主要配置MyBatis的数据源(DataSource),事务管理(TransactionManager),以及打印SQL语句,开启二级缓存,设置实体类别名等功能。
Mapper.xml的作用是什么?我们之前介绍过,MyBatis是"半自动"的ORM框架,即SQL语句需要开发者自定义,MyBatis的关注点在POJO与SQL之间的映射关系。那么SQL语句在哪里配置自定义呢?就在Mapper.xml中配置。
首先来介绍Mapper.xml常用属性:
parameterType:参数数据类型
(1)基本数据类型,通过id查询User。
UserDAO:
//通过id查询User
public User getById(int id);
UserDAO.xml:
<select id="getById" parameterType="int" resultType="com.southwind.entity.User">
select * from user where id=#{id}
</select>
(2)String类型,通过name查询User。
UserDAO:
//通过name查询User
public User getByName(String name);
UserDAO.xml:
<select id="get2" parameterType="java.lang.String" resultType="com.southwind.entity.User">
select * from user where name = #{name}
</select>
(3)包装类,通过id查询User。
UserDAO:
//通过id查询User
public User getById(Integer id);
UserDAO.xml:
<select id="getById" parameterType="java.lang.Integer" resultType="com.southwind.entity.User">
select * from user where id=#{id}
</select>
(4)多个参数,通过name和age查询User。两个参数分别是String类型和int类型,类型不一致,所以此时parameterType可以省略,通过参数下标取出参数值。
UserDAO:
//通过name和age查询User
public User getByNameAge(int id,String name);
UserDAO.xml:
<select id="getByNameAge" resultType="com.southwind.entity.User">
select * from user where name = #{0} and age = #{1}
</select>