当前位置:   article > 正文

Mybatis:传参+提交事务(自动or手动)+sql多表关联查询(两种方法)_mybatis手动提交

mybatis手动提交

目录

一、参数两种类型:

二、传参的几种方法:

三、提交事务

四、sql多表关联查询(两种方法)


一、参数两种类型:

1.#{参数}:预编译方式,更安全,只用于向sql中传值;

select * from  admin where account=#{account} and password=#{password}

2.${参数}:将参数直接拼接到sql中 ,主要用来动态的向sql中传列名。

select  * from admin order by ${colum}

二、传参的几种方法:

1.基本类型不需要做任何处理;

2.多个参数使用:@Param("引用名")绑定;
  
3.传多个参数,使用类,传参使用属性名;
 
4.非基本类型需要@Param("colum") 绑定。

三、提交事务

由于mybatis默认是关闭事务自动提交的:

1.手动提交: 

如果进行了数据库的insert、update、delete操作,修改了数据库,必须必须调用sqlSession.commit()方法,手动提交。

2.自动提交:

将openSession方法中参数值改为true——sessionFactory.openSession(true);

四、sql多表关联查询(两种方法)

有student学生信息表、dorm宿舍信息表、admin管理员信息表,现已查询每个宿舍信息以及每个宿舍所住的学生为例:

相关类:

 

 

 表信息:

admin表

 dorm表

 

 student表

 1.sql查询语句已关联表

        将需要的数据统一用一条sql语句关联表查询,再通过反射存储到相应的类中,由于有一对多的查询(一个宿舍有多个学生)结果,需要使用collection标签。

  1. <resultMap id="dormMap" type="Dorm">
  2. <id column="id" property="id"></id>
  3. <result column="num" property="dormNum"></result>
  4. <association property="admin" javaType="Admin">
  5. <result column="account" property="account"></result>
  6. </association>
  7. <collection property="students" javaType="list" ofType="Student">
  8. <result column="snum" property="num"></result>
  9. <result column="name" property="name"></result>
  10. </collection>
  11. </resultMap>
  12. <select id="findDormById" resultType="com.ffyc.mybatispro.model.Dorm" resultMap="dormMap">
  13. SELECT
  14. d.id,
  15. d.num,
  16. s.num snum,
  17. s.name,
  18. a.account
  19. FROM
  20. dorm d
  21. LEFT JOIN admin a
  22. ON d.adminid = a.id
  23. LEFT JOIN student s
  24. ON s.dormid = d.id
  25. WHERE d.id = #{id}
  26. </select>
  27. <select id="findDorms" resultMap="dormMap">
  28. SELECT
  29. d.id,
  30. d.num,
  31. s.num snum,
  32. s.name,
  33. a.account
  34. FROM
  35. dorm d
  36. LEFT JOIN admin a
  37. ON d.adminid = a.id
  38. LEFT JOIN student s
  39. ON s.dormid = d.id
  40. </select>

2.分步查询

多表关联查询可以分解为多个sql语句逐次查询出需要数据,每次查出的结果可以作为下次查询的条件。

  1. <resultMap id="dormMap1" type="Dorm">
  2. <id column="id" property="id"></id>
  3. <result column="num" property="dormNum"></result>
  4. <association property="admin" javaType="Admin" column="adminid" select="findAdminByid1"></association>
  5. <collection property="students" javaType="list" ofType="student" column="id" select="findStudentByDormid"></collection>
  6. </resultMap>
  7. <select id="findDorms1" resultMap="dormMap1">
  8. select id,num,adminid from dorm
  9. </select>
  10. <select id="findAdminByid1" resultType="Admin">
  11. select account from admin where id = #{adminid}
  12. </select>
  13. <select id="findStudentByDormid" resultType="Student">
  14. select name,num from student where dormid=#{id}
  15. </select>

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号