赞
踩
目录
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);
有student学生信息表、dorm宿舍信息表、admin管理员信息表,现已查询每个宿舍信息以及每个宿舍所住的学生为例:
相关类:
表信息:
admin表
dorm表
student表
1.sql查询语句已关联表
将需要的数据统一用一条sql语句关联表查询,再通过反射存储到相应的类中,由于有一对多的查询(一个宿舍有多个学生)结果,需要使用collection标签。
- <resultMap id="dormMap" type="Dorm">
- <id column="id" property="id"></id>
- <result column="num" property="dormNum"></result>
- <association property="admin" javaType="Admin">
- <result column="account" property="account"></result>
- </association>
-
- <collection property="students" javaType="list" ofType="Student">
- <result column="snum" property="num"></result>
- <result column="name" property="name"></result>
- </collection>
- </resultMap>
- <select id="findDormById" resultType="com.ffyc.mybatispro.model.Dorm" resultMap="dormMap">
- SELECT
- d.id,
- d.num,
- s.num snum,
- s.name,
- a.account
- FROM
- dorm d
- LEFT JOIN admin a
- ON d.adminid = a.id
- LEFT JOIN student s
- ON s.dormid = d.id
- WHERE d.id = #{id}
- </select>
- <select id="findDorms" resultMap="dormMap">
- SELECT
- d.id,
- d.num,
- s.num snum,
- s.name,
- a.account
- FROM
- dorm d
- LEFT JOIN admin a
- ON d.adminid = a.id
- LEFT JOIN student s
- ON s.dormid = d.id
-
- </select>

2.分步查询
多表关联查询可以分解为多个sql语句逐次查询出需要数据,每次查出的结果可以作为下次查询的条件。
- <resultMap id="dormMap1" type="Dorm">
- <id column="id" property="id"></id>
- <result column="num" property="dormNum"></result>
- <association property="admin" javaType="Admin" column="adminid" select="findAdminByid1"></association>
- <collection property="students" javaType="list" ofType="student" column="id" select="findStudentByDormid"></collection>
- </resultMap>
-
- <select id="findDorms1" resultMap="dormMap1">
- select id,num,adminid from dorm
- </select>
- <select id="findAdminByid1" resultType="Admin">
- select account from admin where id = #{adminid}
- </select>
- <select id="findStudentByDormid" resultType="Student">
- select name,num from student where dormid=#{id}
- </select>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。