Mybatis
查询语句的入参类型
基本类型
javabean类型:使用时要与 属性名对应 根据对象的属性名获取属性值
map类型 :匹配參數集合map中key的名字
数组|list类型:
foreach遍历参数list或者数组
collection=“array” 参数类型 array | list
item : 指代每次循环从集合或者数组中拿出的数据(变量名)
separator: 每个数据之间额分隔符
open: 所有遍历输出的的数据之前以什么内容开始
close : 所有遍历输出的的数最后以什么结束
select * from emp where empno in
<foreach collection="array" item="item" separator="," open="(" close=")">
#{item}
</foreach>
查询语句的返回类型
返回类型为:
list
<select id="queryEmpByNameLike" parameterType="string" resultType="string">
select ename from emp where ename like '%'||#{ename}||'%'
</select>
List<String> list = session.selectList("com.xxxx.mappers.EmpMapper3.queryEmpByNameLike","A");
map
<select id="queryMapById" parameterType="_int" resultType="map">
select empno,ename,sal,comm,deptno from emp where empno = #{id}
</select>
Map<String,Object> map = session.selectOne("com.xxxx.mappers.EmpMapper3.queryMapById",7369);
System.out.println(map);
List
返回的是多条数据时使用
<select id="queryMapByName" resultType="map">
select empno,ename,sal,comm,deptno from emp where ename in (
<foreach collection="list" item="item" separator=",">
#{item}
</foreach>
)
</select>
List<Map<String,Object>> list2 = session.selectList("com.xxxx.mappers.EmpMapper3.queryMapByName", Arrays.asList("SMITH","feng"));
list2.forEach(System.out::println);
Date
Date date = session.selectOne("com.xxxx.mappers.EmpMapper3.queryEmpByDate",7369);
System.out.println(new SimpleDateFormat().format(date));
增加语句
<insert id="addEmp" parameterType="emp">
insert into emp(empno,ename,sal,deptno) values(#{empno},#{ename},#{sal},#{deptno})
</insert>
增删改查的事务问题
测试事务问题 : 没有自动提交,需要手动提交
想要自动提交: openSession(boolean)
手动提交: session.commit() session.rollback()
接口绑定方案
创建接口 抽象方法对应sql语句的输入与输出
定义xml文件与接口名相同
- xml文件名要与接口名保持一致
- namespace属性值 必须与接口的权限定名
- id属性必须与抽象方法名保持一致
- 返回值类型和参数类型与方法的返回值和参数保持一致
注意:如果抽象方法的参数列表只有一个参数,sql语句的占位符的名字可以任意定义
抽象方法的参数列表有多个参数,则sql语句的占位符的名字[arg0, arg1, param1, param2]
实现
SqlSession session = SessionUtils.getSession();
DeptMapper mapper = session.getMapper(DeptMapper.class);
List<Dept> list = mapper.queryDeptById(10,30);
list.stream().forEach(System.out::println);
CRUD
多参数匹配参数名字问题
@Param(“deptno1”) 注解: 解决sql中占位符的名字与方法参数不同名问题
代替arg0 param1
批量CRUD
DELETE
<delete id="deleteDeptByIdSome">
delete from dept where deptno in
<foreach collection="list" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
</delete>
UPDATE
注意: end后面也要加;
<update id="updateDeptByIdSome">
<foreach collection="list" item="item" open="begin" close=";end;" separator=";">
update dept set loc = #{item.loc} where deptno = #{item.deptno}
</foreach>
</update>
INSERT
注意使用的是dual
<insert id="insertDept">
insert into dept
<foreach collection="list" item="item" separator="union">
select #{item.deptno}, #{item.dname}, #{item.loc} from dual
</foreach>
</insert>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)