在我们使用Mybatis框架时,可以知道Mybatis有两个配置文件,一个是主要用来配置数据源(DataSource),事务管理(TranscationManager),事务通知(tx:advice./等, 另外还有一个就是Mapper.xml,其实就是用来配置SQL语句,这也说明了Mybatis是半自动化的ORM框架,不像Hibernate全自动化框架,不需要配置SQL语句。 来看看Mybatis的Mapper.xml配置: 1基本的数据类型: 通过id查询User表中的信息
//parameterType是参数类型(id) resultType是返回结果的参数类型 <select id="findUserById" parameterType="int" resultType="user"> select * from user where id=#{id} </select>使用#可以有效的防止SQL注入,若对于该符号不是很清楚建议看下面这篇文章,Mybatis中${}和#{}的区别 使用这种简单类型的数据,在我们进行查询的时候,可以在查询语句中直接输入对应的值, 2String类型 接下来看看下面这种比较特殊的情况:通过名字进行模糊查询时
${} <select id="selectUserByName" parameterType="string" resultType="user"> select * from user where username like "%${value}%" </select> 进行查询: List<User> list=userMapper.selectUserByName("小明"); #{} <select id="selectUserByName" parameterType="string" resultType="user"> select * from user where username like "%#{value}%" </select> 进行查询: List<User> list=userMapper.selectUserByName("%小明%"); 这个时候,需要加入%号,而${}就不需要, 同时还有一点,在使用Group by 语句时,只能用${},不能用#{}3多个参数时
<select id="getByNameAge" resultType="user"> select * from user where name=#{0} and age=#{1} </select>4进行级联查询 这里进行级联查询的时候,需要在实体类配置两个表之间的关系,一对多或多对一关系配置: 如下,两个实体类: 学生表和成绩表一对多
public class student{ private int id; private String name; private String address; //引入成绩表,又因为学生和成绩为一对多,所以在学生类中需要配置成绩的集合 private List<Source> source; 。。。。。。Source表:
public class student{ private int id; private int grade; //引入学生表,因为成绩表和学生表是多对一关系,所以只需要引入对应的学生类即可 private Student student; 。。。。。。。接着去配置文件中完成映射 首先来配置Student这个类, 1配置student与数据库表的映射关系<resultMap>hibernate是通过<hibernamt-mapping> 2配置该级联查询的List集合, 通过Collection标签将结果映射到对应的属性中 3配置sql语句
ofType:指定映射到LIst集合属性中pojo的类型 property:将关联查询的多条数据映射到Source类属性中
<resultMap type="student" id="studentMap"> <id property="id" column="id“/> <result property="name" column="name"/> <result property="address" column="address"/> <!--一个学生可以有多个成绩所以使用collection 映射Source属性字段.ofType映射实体类,,--> <collection property="source" ofType="source"> <id property="id" column="id"/> <result property="grade" column="grade”/> </collection> </resultMap> <!--配置对应的查询语句,resultMap对应上面配置的resultMap--> <select id=getById" parameterType="int" resultMap="studentMap"> select * from student as s,source sc where s.id=sc.id and s.id=#{}; </select>配置Source表: 1配置该Source表与数据库表source的映射关系 2配置该级联映射 3配置sql数据查询语句
<resultMap type="source" id="sourceMap"> <id property="id" column="id"/> <result property="source" column="source"/> <!--配置与学生一对一的关系,.使用association,j将结果进行级联映射的配置,> <association property="student" javaType="student"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="address" column="address"/> </association> <./resultMap> <!--配置对应的sql查询语句--> <select id=getById" parameterType="int" resultMap="soureceMap"> select * from student as s,source sc where s.id=sc.id and sc.id=#{}; </select>