mybatis配置文件分为两种:
mybatis-config.xml主配置文件 | mapper映射文件 |
---|---|
用来配置环境变量,使用连接池连接数据库,注册mapper配置文件位置 | 用来编写SQL语句,其中namespace为其接口的全限定名称,id为接口中方法的名称 |
填写properties的连接信息<propertise resource="url"/> | parameterType :1.简单数据类型(基本数据类型+String)2.引用数据类型3.如果传参是个map类型,其#{}中必须是其map的key4.传多值可以是实体类或者map类型 |
设置与数据库交互的环境,更加有效的查询表中的记录,但效果不佳<settings><setting name="" value=""/></settings> | #{}防止sql注入,'${}'不能防止sql注入 ,采用拼串原理,模糊查询拼串可以使用补充:mysql中空格相当于加号拼串 |
为mapper文件中的domain下的实体类权限的名称起别名<typeAliases><!--为单个实体类起别名--> <typeAlias type="com.xxx.domain.Student" alias="stu"/><!--自动起别名,别名为类名,不区分大小写--><package name="com.xxx.domain"/></typeAliases> | resultType :1.简单数据类型(基本数据类型+String)2.引用数据类型3.如果返回map类型,其#{}中必须是其map的key4.返回值可以是实体类或者map类型,domain处理不了 |
配置映射文件路径<mappers><!--直接注册文件路径--><mapper resource="com/yixia/dao/StudentDao.xml"/><!--通过接口注册--><mapper class="com.xxx.dao.StudentDao"/><!--通过包批量注册映射文件,推荐--><package name="com.xxx.dao"/></mappers> | 当表中的字段值和domain中类不一样时<!--id为标识名,用于找对该map,Student为和表字段值相符的类--> <resultMap id="stuMap" type="Student"><!--id为主键,result为普通键,property为类中的属性,column为表中的字段值--><id property="id" column="id"/><result property="name" column="funame"/><result property="age" column="age"/></resultMap> |
动态SQL语句
使用where标签和if标签
<select id="selectDuo" resultType="Student">
select * from t_student
<where>
<if test="name!=null and name!=''">
and name like '%' #{name} '%'
</if>
<if test="address!=null and address!=''">
and address like '%' #{address} '%'
</if>
</where>
</select>
接收数组
<select id="selectArr" resultType="Student">
select * from t_student where id in
<!--
collection:标识传递参数的类型
array:数组
list:集合
item:每一次遍历出来的元素,在使用该元素时,需要套用在#{}中
open:拼接循环的开始符号 close:拼接循环的结束符号
元素与元素之间的分隔符
-->
<foreach collection="array" item="id" close=")" open="(" separator=",">
#{id}
</foreach>
</select>
使用SQL标签制作SQL片段
用来代替SQL语句中的代码
<sql id="sql01">
select * from t_student
</sql>
<select id="select01" resultType="Student">
<include refid="sql01"/>
</select>
多表联查
普通形态
<select id="selectJoin" resultType="map">
select
s.name as sname,
c.name as cname
from t_student s
join t_classroom c
on s.classroomId=c.id
</select>
如果需要向前端传输的数据domain不足以满足,可以使用map和vo
vo
创建一个多个实体类的集合,来汇总整个搜索结果
提高查询表效率:
- 设置索引
- 使用nosql数据库,比如redis数据库
- 搜索引擎选择:solr和Elasticsearch,电商使用