Mapper.xml 常用配置
MyBatis 配置文件有两种:
1、全局环境配置文件(数据源、事务管理、Mapper 注册、打印 SQL、惰性加载、二级缓存。。。)
2、Mapper 配置文件(定义自定义接口的具体实现方案:SQL、数据与 POJO 的映射)
多表关联查询包括一对一、一对多、多对多
单表查询
<select id="findById" parameterType="java.lang.Integer"
resultType="com.southwind.entity.People">
select * from people where id = #{id}
</select>
业务:通过 id 查询 People 对象
目标表:test/people
实体类:com.southwind.entity.People
Mapper.xml 设置相关配置逻辑,由 MyBatis 自动完成查询,生成 POJO。
statement 标签主要属性有 id、parameterType、resultType,id 对应接口的方法名,parameterType 定义参数的数据类型、resultType 定义查询结果的数据类型(实体类的成员变量列表必须与目标表的字段列表一致)
paramterType
支持基本数据类型、包装类、String、多参数、POJO 等。
1、基本数据类型,通过 id 查询 POJO。
public People findById(int id);
<select id="findById" parameterType="int"
resultType="com.southwind.entity.People">
select * from people where id = #{num}
</select>
2、包装类
public People findById(Integer id);
<select id="findById" parameterType="int"
resultType="com.southwind.entity.People">
select * from people where id = #{num}
</select>
3、String 类型
public People findByName(String name);
<select id="findByName" parameterType="java.lang.String"
resultType="com.southwind.entity.People">
select * from people where name = #{name}
</select>
4、多参数
public People findByIdAndName(Integer id,String name);
<select id="findByIdAndName" resultType="com.southwind.entity.People">
select * from people where id = #{id} and name = #{name}
</select>
5、POJO
public int update(People people);
<update id="update" parameterType="com.southwind.entity.People">
update people set name = #{name},money = #{money} where id = #{id}
</update>
resultType
resultType 与 parameterType 的使用基本⼀致。
1、基本数据类型
public int count();
<select id="count" resultType="int">
select count(*) from people
</select>
2、包装类
public Integer count();
<select id="count" resultType="java.lang.Integer">
select count(*) from people
</select>
3、String
public String findNameById(Integer id);
<select id="findNameById" parameterType="java.lang.Integer"
resultType="java.lang.String">
select name from people where id = #{id}
</select>
4、POJO</