mybatis数据操作总结

1. Namespace

1.1. 当前XxxMapper.xml文件针对哪个接口

1.2. 接口写全称

2. 配置文件实现接口的步骤

2.1. 通过配置select,insert,update,delete节点并拼写sql语句实现接口

2.2. ID 方法名

2.3. parameterType 接口方法的参数类型(如果方法有多个参数,则可以省略)

3. 复杂参数的接口方法的映射配置

3.1. 一个参数

3.1.1. 基本类型

Emp findEmpById(

//为接口方法参数命别名,方便在映射文件中使用#{别名}代表传入的参数值

@Param("abcd") int id);

<select id="findEmpById" parameterType="int" resultMap="empMap">

<!-- 接口方法参数没有别名情况下,#{任意字符} -->

select * from emp where empid=#{abcd}

</select>

3.1.2. 对象类型

Int updateEmp(Emp emp);

<update id=”updateEmp” parameterType=”com.entity.Emp”>

Update emp set ename=#{emp.ename} where empid=#{emp.empid}

</update>

3.2. 多个参数

List<Emp> findEmpByCondition(

@Param("empid")

int id,

@Param("emp")

Emp emp);

<select id="findEmpByCondition" resultMap="empMap">

<!-- 如果多个参数中存在对象类型,则使用#{别名.属性名} -->

select * from emp where empid=#{empid} and ename=#{emp.name}

</select>

 

Emp login(int id,String name);

<select id="login" resultMap="empMap">

select * from emp where empid=#{0} and ename=#{1}

</select>

 

Emp login(

@Param("empid")

int id,

@Param("ename")

String name);

<select id="login" resultMap="empMap">

select * from emp where empid=#{empid} and ename=#{ename}

</select>

4. ResultMap和ResultType

4.1. ResultMap 程序员根据业务需要自定义的属性名与列名的映射关系,如果属性名与列名不一致

4.2. ResultType 接口方法返回值集合的元素类型,一般就是实体类的类型

4.3. ResultMap可以根据需要,配置多个映射方案

5. Mybatis实现分页查询

5.1. 设计接口方法

List<Emp> findEmpByCondition2(HashMap map);

5.2. XxxMapper.xml

<!-- 将需要传递到sql语句的所有参数都通过键值对方式由外界传递进来 -->

<select id="findEmpByCondition2" resultMap="empMap">

SELECT * FROM (

        SELECT e.*,ROWNUM r FROM emp e

        WHERE e.ename like #{eu.name}

        and e.hiredate >= #{eu.startDate}

        and e.hiredate <= #{eu.endDate}

        and e.deptid=#{eu.deptid}

        and ROWNUM <=#{start}

)WHERE r>#{end}

</select>

5.3. 测试类

//定义分页查询需要的所有条件

int pageIndex=1;

int pageSize=5;

 

//多条件采用帮助类形式保存

EmpUtil eu=new EmpUtil("%刘%", EmpUtil.stringToDate("2015-01-01"), EmpUtil.stringToDate("2018-12-31"), 3);

 

HashMap map=new HashMap();

//将所有条件以键值对的方式保存在HashMap

//配置文件将以键获取对应的数据

map.put("eu", eu);

map.put("start", pageSize*pageIndex);

map.put("end",pageSize*(pageIndex-1));

List<Emp> emps= ed.findEmpByCondition2(map);

 

for (Emp emp : emps) {

System.out.println(emp);

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值